Is there a reliable way to execute a page script at document_start

Let’s say, I have a page.js which contains codes need to be run at document_start as page script. The script must be executed before any code the page provided. The script need to access variables on window, so it have to be an page script not content script.

Is there a reliable way to execute the page.js in pages’ context before any other code? How can I do that?

1 Like

run_at: “document_start” isn’t reliable? I haven’t tried it myself.

I’m asking for page script.

I don’t know how a page script is different from a content script. We are talking about injecting a script into the page using an extension, correct?

I think he wants to execute his own content script in a page but it must run before the page executes its own scripts.

But I’m not sure about accessing window variables of the page script from your content script…
MDN says it’s not possible:

The same is true in reverse; page scripts cannot see JavaScript properties added by content scripts.

This means that content scripts can rely on DOM properties behaving predictably, without worrying about its variables clashing with variables from the page script.

One practical consequence of this behavior is that a content script doesn’t have access to any JavaScript libraries loaded by the page. So, for example, if the page includes jQuery, the content script can’t see it.

I think I want to execute my own PAGE SCRIPT, not content script.

Ok so I’m no expert in this area but I guess if you relax some of the CSP, you should be able to edit DOM and inject your own script to the page.

This may pose a issue for an AMO reviewer though.

You can create a script element and append it to the document.

var script = document.createElement(‘script’);

documentElement needs to be added for it to work.

And set run_at to document_start.