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?
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?
Share Improve this question edited Aug 31, 2012 at 7:57 Wladimir Palant 57.7k12 gold badges99 silver badges127 bronze badges asked Aug 30, 2012 at 9:55 David TuiteDavid Tuite 22.7k25 gold badges115 silver badges179 bronze badges2 Answers
Reset to default 6Don'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 plicated 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/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/show_bug.cgi?id=787063