Vighnesh Raut
Vighnesh Raut

Reputation: 23

How to inject script on a Webpage?

I have many websites that has the following script tag in the head section:

<html>
    <head>
        <script>
            window.doSomething(someObject);
        </script>
    </head>
    <body>
         .....
    </body>
</html>

Now, I want to inject a script before any page loads so that these websites will have the access to the function doSomething which is defined my custom script. How do I make sure that my custom script is executed before any of the scripts in the HTML file?

I don't want to modify the front-end code. I thought of using extensions but they run after all the scripts on the page. Is there a way I can do this?

Even a Chrome specific way would suffice.

Upvotes: 0

Views: 659

Answers (1)

Thomas
Thomas

Reputation: 182063

Declaratively injected scripts in Chrome extensions can be configured to run at document start:

{
  "name": "My extension",
  ...
  "content_scripts": [
    {
      "matches": ["http://*.nytimes.com/*"],
      "run_at": "document_start",
      "js": ["contentScript.js"]
    }
  ],
  ...
}

Unfortunately that's not the whole story, because injected scripts run in an isolated environment, so you can't modify the window object of the page itself. You can, however, modify the DOM (which is still empty at this point) to add a <script> element that loads a script from your extension, as described in Method 1 in this answer. That second script will then run in the context of the page itself, and can do whatever it likes.

Upvotes: 1

Related Questions