Chrome扩展程序 - 覆盖.js文件 [英] Chrome Extension - override .js file

查看:365
本文介绍了Chrome扩展程序 - 覆盖.js文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个网站在JS文件中有一定的错误。 JS文件只在一个地方被引用:

 < script type =text / javascriptcharset =utf- 8src =/ r / js / no-closure / dialogs.js?v = 2>< / script> 

我已经下载了JS文件并修正了错误。有什么办法可以通过Chrome扩展,用我的 dialogs_fixed.js覆盖 /r/js/no-closure/dialogs.js



我试过了( background.js ):

  var script = $('[src * =dialogs.js]'); 
script.attr(src,dialogs_patch.js);

没有运气。

解决方案

您不需要为此使用实验性webRequest,您可以使用beforeload事件。
这样的东西应该可以工作....

  String.prototype.endsWith = function(pattern){
var d = this.length - pattern.length;
返回d> = 0&& this.lastIndexOf(pattern)=== d;
};

document.addEventListener('beforeload',function(event){
if(event.url.endsWith(/ r / js / no-closure / dialogs.js?v = 2 )){event.srcElement.src = chrome.extension.getURL(dialogs.js);}
},true);

..把它放在一个内容脚本中,以你感兴趣的页面为目标。
并使确保您在页面添加之前加载此内容脚本...

 run_at:document_start

...您的内容脚本字段....



http://code.google.com/chrome/extensions/content_scripts.html

编辑
应该注意的是,从Chrome 17开始,web请求API不再是实验性的,而是一个很好的重定向方式。


There is a website that has a certain bug in the JS file. The JS file is only being referenced in one place:

    <script type="text/javascript" charset="utf-8" src="/r/js/no-closure/dialogs.js?v=2"></script>

I've downloaded the JS file and fixed the bug. Is there any way I can, via a chrome extension, override the /r/js/no-closure/dialogs.js with my dialogs_fixed.js?

I've tried (in background.js):

var script = $('[src*="dialogs.js"]');
script.attr("src", "dialogs_patch.js");

No luck.

解决方案

You dont need to use the experimental webRequest for this, you could just use the beforeload event. Something like this should work....

String.prototype.endsWith = function(pattern) {
    var d = this.length - pattern.length;
    return d >= 0 && this.lastIndexOf(pattern) === d;
};

document.addEventListener('beforeload', function(event) {
if (event.url.endsWith("/r/js/no-closure/dialogs.js?v=2")){event.srcElement.src=chrome.extension.getURL("dialogs.js");}
}, true);

..put that in a content script targeting the page your interested in. And make sure you make this content script load before the page does by adding...

"run_at" : "document_start"

...to your content scripts field....

http://code.google.com/chrome/extensions/content_scripts.html

EDIT Altho it should be noted that as of Chrome 17 the web request api is no longer experimental and is a great way to do redirects.

这篇关于Chrome扩展程序 - 覆盖.js文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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