Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

google chrome extension - document.body is null in popup js file

I started out with hello world application from google documentation to write a chrome extension. http://code.google.com/chrome/extensions/getstarted.html

I simply modified the popup.js to be:

var span = document.createElement("span");
span.innerHTML = "<b>blah</b>";
alert(document.head);
alert(document.body);
document.body.appendChild(span);

I expect this to display "blah" in my popup but I am getting document.body as null. I am new to js and chrome and my trying to figure out whats going on here. What am I doing wrong?

like image 438
grasaved Avatar asked Apr 21 '12 21:04

grasaved


People also ask

Why is document body null?

body object, it is most likely because the body has not been defined yet. If document. body is null, you most likely need to execute your code in the window. onload function.

What is Chrome scripting executeScript?

executeScript() Injects a script into a target context. The script is run at document_idle by default. Note: This method is available in Manifest V3 or higher in Chrome and Firefox 101. In Safari and Firefox 102+, this method is also available in Manifest V2.

What is content JS in Chrome extension?

Content scripts are JavaScript files that run in the context of web pages. By using the standard Document Object Model (DOM), they can read details of the web pages the browser visits, or make changes to them.

Do Chrome extensions use JavaScript?

A chrome extension is a program that is installed in the Chrome browser that enhances the functionality of the browser. You can build one easily using web technologies like HTML, CSS, and JavaScript. Creating a chrome extension is similar to creating a web application, but it requires a manifest.


2 Answers

The DOM does not exist yet when the popup script runs. You need to listen to a DOMContentLoaded event in your popup script.

Something like this would work:

  document.addEventListener('DOMContentLoaded', function(event) {
    console.log(document.body);
  });
like image 182
dipole_moment Avatar answered Oct 12 '22 11:10

dipole_moment


When the closing script tag is encontered, the corresponding code is directly evaluated.

Since background.js is loaded in the head, <body> does not exist (yet). Hence, document.body is null.

like image 34
Rob W Avatar answered Oct 12 '22 09:10

Rob W