Chrome extension to modify page's script includes and JS

I've done a fair amount of Chrome extension development, and I don't think there's any way to edit a page source before it's rendered by the browser. The two closest options are:

  • Content scripts allow you to toss in extra JavaScript and CSS files. You might be able to use these scripts to rewrite existing script tags in the page, but I'm not sure it would work out, since any script tags visible to your script through the DOM are already loaded or are being loaded.

  • WebRequest allows you to hijack HTTP requests, so you could have an extension reroute a request for library.js to library_dev.js.

Assuming your site is www.mysite.com and you keep your scripts in the /js directory:

chrome.webRequest.onBeforeRequest.addListener(
    function(details) {
        if( details.url == "http://www.mysite.com/js/library.js" )
            return {redirectUrl: "http://www.mysite.com/js/library_dev.js" };
    },
    {urls: ["*://www.mysite.com/*.js"]},
    ["blocking"]);

The HTML source will look the same, but the document pulled in by <script src="library.js"></script> will now be a different file. This should achieve what you want.


Here's a way to modify content before it is loaded on the page using the WebRequest API. This requires the content to be loaded into a string variable before the onBeforeRequest listener returns. This example is for javascript, but it should work equally well for other types of content.

chrome.webRequest.onBeforeRequest.addListener(
    function (details) {
        var javascriptCode = loadSynchronously(details.url);
        // modify javascriptCode here
        return { redirectUrl: "data:text/javascript," 
                             + encodeURIComponent(javascriptCode) };
    },
    { urls: ["*://*.example.com/*.js"] },
    ["blocking"]);

loadSynchronously() can be implemented with a regular XMLHttpRequest. Synchronous loading will block the event loop and is deprecated in XMLHttpRequest, but it is unfortunately hard to avoid with this solution.