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

标签 jquery google-chrome-extension

我正在尝试将远程脚本作为 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/

相关文章:

javascript - jQuery ui 选项卡选择所需的帮助。我可以取消该操作吗?

javascript - 使用 load() 加载 html 页面后,jQuery 单击事件处理程序不起作用

javascript - 使用 Chrome 扩展内容脚本注入(inject) Angular 8 应用程序

javascript - Chrome Web 扩展因 "Disable developer mode extensions"Chrome 弹出窗口而停止

javascript - 如何通过扩展程序获取(不设置)Chrome 中选定文本的背景颜色?

javascript - 网页 : List remote FTP files via links that download them

"static method"上的 JavaScript 回调

javascript - 尝试使可拖动的表单元素水平 jQuery

javascript - 对 Tumblr 的 API 调用没有回调

javascript - 为什么在 Chrome 选项卡中更改 url 在输入指定 url 时不会更新选项卡 Url?