简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM