Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing the window object in Firefox addon content script?

I can't seem to access the window object in a content script. Is this normal?

For example, this does nothing:

window.onload = function() {
  console.log("Hello from the onload");
};

Instead, I have to use the unsafeWindow object.

unsafeWindow.onload = function() {
  console.log("Hello from the onload");
};

I must be missing something simple right?

like image 501
David Tuite Avatar asked Jul 29 '26 02:07

David Tuite


2 Answers

Don't use window.onload, instead write:

window.addEventListener("load", function() {
  console.log("Hello from the onload");
}, false);

window.onload has the limitation that there can only be one event listener, setting a different listener replaces the existing one - that's already a reason why you should never use it. In case of the Add-on SDK things get more complicated because the content script has a different view of the DOM then the web page. So just use addEventListener.

Oh, and please don't use unsafeWindow - it is (as the name already says) inherently unsafe.

The window object available to you in a content script is actually a proxy - hence unsafeWindow works and window does not. I did some tests and document.addEventListener does not work either:

https://builder.addons.mozilla.org/package/150362/latest/

jQuery seems to work fine though, I imagine there is some magic they do to ensure that they fire no matter what.

The workaround is simply set contentScriptWhen to 'end' and run your code immediately - this should always work as the content script is attached when the document is finished loading.

I did log this bug regarding what I like to think of as the 'wtf?' aspect of this behaviour - I think the result is surprising to web developers and we should try to be less surprising:

https://bugzilla.mozilla.org/show_bug.cgi?id=787063

like image 23
therealjeffg Avatar answered Jul 31 '26 14:07

therealjeffg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!