Sjoerd
Sjoerd

Reputation: 75568

Override JavaScript function from browser extension

I am creating a web extension to help detecting postMessage activity in websites. Therefore, I want to detect it when a page attaches a message event listener, for example by calling this code:

window.addEventListener("message", ...)

Apparently it is not possible to get a list of event listeners. My next idea was to override addEventListener, so I can detect calls to it:

window.addEventListener = function(type) {
    if (type == "message") {
        // do something
    }
}

I have trouble injecting this code into the page:

How can I override window.addEventListener globally from my extension? Or alternatively, is there another way to detect an event listener on message events?

Upvotes: 9

Views: 4963

Answers (1)

Sjoerd
Sjoerd

Reputation: 75568

To override a function, you need to run JavaScript before the page loads. You need to do the following:

  • In the manifest.json, specify that the content script is run before the document is loaded by setting run_at to document_start.
  • From the content script, inject static code into the page. Don't use an URL, but create a script tag that contains the code. I.e. script.textContent = actualCode and not script.src = url.

Upvotes: 6

Related Questions