我正在尝试将远程脚本作为 Chrome 扩展中的内容脚本注入,但我觉得我正在运行 Chrome 执行环境的模糊(至少对我而言)区域。
我想将 jQuery$.getScript
用于那个(和其他)目的。
这是注入代码(这里非常推荐):
// 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");
错误是:"$ is not defined"
错误中$
提到的似乎是myremotescript.js
函数的错误,因为如果myremotescript.js
更改为:
document.body.style.backgroundColor = "green";
似乎不仅$
没有定义。如果我myremotescript.js
改为:
function Do(){
document.body.style.backgroundColor = "green";
}
然后从以下回调执行 Do() $.getScript
:
chrome.tabs.executeScript(null, {
code: '$.getScript("https://mysite.com/myremotescript.js", function(){ Do(); })'
});
那么错误是:"Do is not defined"
有什么想法/解释/建议吗?
编辑:解决方案:按照@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();" });
});
})