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?
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.
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.
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.
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.
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);
});
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With