Chrome扩展程序修改页面的脚本包括和JS [英] Chrome extension to modify page's script includes and JS

查看:536
本文介绍了Chrome扩展程序修改页面的脚本包括和JS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用客户在其网站上包含的一个JavaScript库来嵌入UI小部件。我希望有一种方法可以在客户的网站上直接测试该库的开发版本,而不需要对其代码进行任何更改。这样可以很容易地调试问题并测试新版本。



为此,我需要将脚本include改为指向我的开发服务器,然后覆盖load ()方法,在页面中调用它来添加一个额外的参数来告诉它在进行远程调用时指向什么服务器。



它看起来像我可以将JS添加到页面使用铬扩展,但我没有看到任何方式来修改加载之前的页面。有没有我缺少的东西,或者铬扩展是不允许做这种事情的? 我已经完成了大量的Chrome扩展开发,我认为在浏览器呈现它之前,没有办法编辑页面源代码。最接近的两个选项是:



假设您的网站是www.mysite.com,并且您的脚本保持在/ js目录:

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

HTML源文件看起来是一样的,但文件被< ;脚本src =library.js>< / script> 现在将成为不同的文件。这应该达到你想要的。


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 without requiring them to make any changes to their code. This would make it easy to debug issues and test new versions.

To do this I need to change the script include to point to my dev server, and then override the load() method that's called in the page to add an extra parameter to tell it what server to point to when making remote calls.

It looks like I can add JS to the page using a chrome extension, but I don't see any way to modify the page before it's loaded. Is there something I'm missing, or are chrome extensions not allowed to do this kind of thing?

解决方案

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.

这篇关于Chrome扩展程序修改页面的脚本包括和JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆