Reputation: 96
window.my_property = "my_property";
I want to my snippet run before other js scripts on the website. Is it possible? Thanks in advance.
Upvotes: 2
Views: 698
Reputation: 1275
The most easy and temporary way to run chrome js Snippets before page load is to put debugger
at the top of your HTML page, preferably at head or before the js code which relies on your js snippet.
<head>
<script>
debugger;
</script>
...
Now when the browser is "Paused in debugger", right click on the snippet name and Run it to execute immediately. After that you can resume debugger and continue working on the page as usual.
Please remember, this method is suitable only for testing and requires you to have control over the page (as you need to edit page HTML or JS to put debugger
)
If you need to run your js snippet every-time or the page is not in your control, creating an chrome extension is currently the only solution.
Upvotes: 0
Reputation: 77482
It's possible using Chrome Extensions.
You can write an extension (how to do that is beyond the scope of the answer - see some guides in the docs) that injects a Content Script with "run_at": "document_start"
configuration and match patterns that fit the pages you want to inject it to.
Then, your code executes before the page is loaded - it basically consists only of the document
node at that point. If you need to manipulate nodes, you're out of luck - some scripts will probably execute before the node is in the tree. If you just want to execute something like the above (modify the window
object), you'll be able to do so.
Yet still, you'll need to make it a bit more complicated because of the isolated world principle. You need to use a technique to inject your code into the page.
You can do it way more easily by using a userscript engine like Tampermonkey. Again, you'll need something like
// @run-at document-start
How to write a userscript is, again, beyond the scope of this answer.
Upvotes: 2