远程脚本作为 Chrome 扩展程序中的内容脚本

New*_*Dev 5 jquery google-chrome-extension

我正在尝试将远程脚本作为 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(){ })' });
});
Run Code Online (Sandbox Code Playgroud)

这是远程脚本 myremotescript.js- 很简单:

$("body").css("backgroundColor", "green");
Run Code Online (Sandbox Code Playgroud)

错误是"$ is not defined"

错误中提到$的似乎是函数的函数myremotescript.js,因为如果myremotescript.js更改为:它就可以工作:

document.body.style.backgroundColor = "green";
Run Code Online (Sandbox Code Playgroud)

看来不仅没有$定义。如果我更改myremotescript.js为:

function Do(){
    document.body.style.backgroundColor = "green";
}
Run Code Online (Sandbox Code Playgroud)

然后从回调中执行 Do() $.getScript

chrome.tabs.executeScript(null, {
    code: '$.getScript("https://mysite.com/myremotescript.js", function(){ Do(); })' 
});
Run Code Online (Sandbox Code Playgroud)

那么错误是:"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();" });
    });
})
Run Code Online (Sandbox Code Playgroud)

Rob*_*b W 1

$.getScript默认注入一个<script>元素来加载来自不同来源的脚本。因此,代码在页面上下文中运行,而不是在内容脚本中运行(另请参阅)。

如果你确实想使用 jQuery 来获取脚本,请替换

$.getScript("https://mysite.com/myremotescript.js", function(){ });
Run Code Online (Sandbox Code Playgroud)

具有以下内容(eval用作回调,因此它评估请求的响应)

$.get("https://mysite.com/myremotescript.js", eval);
Run Code Online (Sandbox Code Playgroud)

虽然这有效,但我建议缓存脚本的响应正文。这样,即使网络连接中断,您的分机也不会中断。而且,更重要的是,用户不会在每次页面加载时收到无用的请求。我之前已经充实了这个概念,请参阅这个答案