javascriptgoogle-chrome-extensioninstrumentationjavascript-injection

Adding instrumentation (aka injecting into scripts) using chrome extensions


My goal is to inject instrumentation code into certain scripts of certain websites to then lately collect the data using chrome extension and upload it to a centralized DB.

The last time I tried this was around 2016 when I achieved this using "onbeforescriptexecute" in a user script I added to firefox using GreaseMonkey, back then chrome didn't support this at all. Now I've looked around here and the newest I found was around the same yeah mentioning "onbeforescriptexecute" is not supported in chrome and offering a workaround with a link to a GitHub page that no longer exists.

So are there any modern ways to intercept scripts loading into a web page in chrome extension content script? What I need is to catch each script before it loads, parse, inject instrumentation and then proceed to run it.


Solution

  • From what I understand, you want to intercept every script and manipulate the contents of the script before it is being executed in the browser.

    The short answer is No. You cannot intercept external scripts using Chrome Extension Content Scripts but you can intercept using webRequestAPI in Manifest V2 (Note - It's going away soon)

    Your best bet is to write a Proxy application that intercepts the scripts and modifies the contents of the scripts as per the User or your business logic.

    We have solved a similar problem at Requestly by offering a desktop app-based solution So you can launch a browser from the Requestly Desktop App and then create Modify Response Rule in the Desktop App which allows you to define a static response or change the existing response pragmatically.

    Launching Apps

    enter image description here

    Modifying Response Pragmatically

    Change Response Programatically

    Once you do this, your scripts will be intercepted and your code will run on top of the existing responses from the server.

    You can build a similar application like this for your case. I am afraid this isn't possible with Chrome Extensions.