patchrail
patchrail

Reputation: 2007

Missing properties in window when using a content script

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

Answers (1)

Wladimir Palant
Wladimir Palant

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 an XPCNativeWrapper of a DOM node or Window object will throw an exception. (Use addEventListener instead, and use event.preventDefault(); in your handler if you used return 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.

Additional reading

Upvotes: 2

Related Questions