我正在尝试将远程脚本作为 Chrome 扩展程序中的内容脚本注入(inject),但我感觉自己正在进入 Chrome 执行环境的黑暗区域(至少对我而言)。
我想使用 jQuery 的 $.getScript
来实现该(和其他)目的。
这是注入(inject)代码(非常出色 suggested here ):
// inject jQuery
chrome.tabs.executeScript(null, { file: "js/jquery.js" }, function() {
// inject remote script with jQuery
chrome.tabs.executeScript(null, { code: '$.getScript("https://mysite.com/myremotescript.js", function(){ })' });
});
这是远程脚本 myremotescript.js
- 很简单:
$("body").css("backgroundColor", "green");
错误是:“$未定义”
错误中引用的 $
似乎是 myremotescript.js
函数的函数,因为如果 myremotescript.js
发生更改,它就会起作用至:
document.body.style.backgroundColor = "green";
看来不仅是 $
没有定义。如果我将 myremotescript.js
更改为:
function Do(){
document.body.style.backgroundColor = "green";
}
然后从$.getScript
的回调中执行Do():
chrome.tabs.executeScript(null, {
code: '$.getScript("https://mysite.com/myremotescript.js", function(){ Do(); })'
});
错误是:“Do 未定义”
有什么想法/解释/建议吗?
编辑:解决方案:按照@Rob-W回答,它起作用了。为了让 $.get()
不出错,我需要添加的唯一怪癖是将数据类型标记为“文本”。另外,我不需要执行 eval
,因为 executeScript
可以接受代码作为文本:
$.get("https://mysite.com/myremotescript.js", null, null, "text")
.done(function(remoteCode){
chrome.tabs.executeScript(null, { code: remoteCode }, function(){
chrome.tabs.executeScript(null, { code: "Do();" });
});
})
最佳答案
$.getScript
默认注入(inject) <script>
元素从不同来源加载脚本。因此,代码在页面上下文中运行,而不是在内容脚本 ( see also ) 中运行。
如果你确实想使用jQuery来获取脚本,请替换
$.getScript("https://mysite.com/myremotescript.js", function(){ });
具有以下内容(eval
用作回调,因此它评估请求的响应)
$.get("https://mysite.com/myremotescript.js", eval);
虽然这有效,但我建议缓存脚本的响应正文。这样,即使网络连接中断,您的分机也不会中断。而且,更重要的是,用户不会在每次页面加载时收到无用的请求。我之前已经充实过这个概念,请参阅this answer .
关于jquery - 远程脚本作为 Chrome 扩展程序中的内容脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18169666/