Reputation: 2007
My addon is injecting some content scripts into various websites. After trying to bind onbeforeunload
or calling window.location.reload
I realized that the window object misses some properties.
Is there a way to binding certain events (onbeforeunload
, onunload
, etc) while injecting code via page-mod
module?
I've created a test add-on, showing that these properties are missing: https://builder.addons.mozilla.org/addon/1037497/latest/
Solutions on how to use them anyway?
Upvotes: 1
Views: 193
Reputation: 57671
Short answer: You add an event listener using addEventListener()
method, like this:
window.addEventListener("beforeunload", function(event)
{
...
}, false);
Long answer: For security reasons your content script isn't communicating with the DOM objects directly, e.g. it cannot see any script-added properties. The technical details also list some limitations:
Assigning to or reading an
on*
property on anXPCNativeWrapper
of a DOM node or Window object will throw an exception. (UseaddEventListener
instead, and useevent.preventDefault();
in your handler if you usedreturn false;
before.)
In a content script you probably don't want to replace the web page's event handlers anyway, rather add your own - that's what addEventListener()
is doing.
Upvotes: 2