4

我正在尝试将远程脚本作为 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();" });
    });
})
4

1 回答 1

1

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

如果你真的想使用jQuery来获取脚本,替换

$.getScript("https://mysite.com/myremotescript.js", function(){ });

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

$.get("https://mysite.com/myremotescript.js", eval);

虽然这可行,但我建议缓存脚本的响应正文。然后,如果网络连接断开,您的扩展程序不会中断。而且,更重要的是,用户不会在每次页面加载时都收到无用的请求。我之前已经充实了这个概念,请参阅这个答案

于 2013-08-11T10:50:42.167 回答