Chrome extension to modify page's script includes and JS

前端 未结 5 1777
名媛妹妹
名媛妹妹 2020-12-13 13:51

I work on a javascript library that customers include on their site to embed a UI widget. I want a way to test dev versions of the library live on the customer\'s site with

5条回答
  •  被撕碎了的回忆
    2020-12-13 14:34

    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.

提交回复
热议问题