【问题标题】:Why cant content scripts use the jQuery loaded on the background page?为什么内容脚本不能使用后台页面加载的 jQuery?
【发布时间】:2012-03-06 23:48:29
【问题描述】:

我正在构建我的第一个扩展程序,但在让后台页面加载脚本在内容脚本中工作时遇到问题,这让人怀疑后台页面上加载的任何脚本是否真的可用于所有内容脚本。

我有两个 javascript 文件,functions.js 和 content.js,它们都使用 jQuery。我在后台页面加载 jQuery 和函数脚本以减少每个站点匹配的解析。一次就够了,因为它们都是函数。

ma​​nifest.json 无效

{
  "name": "extension name",
  "background_page": "background.html",
  "content_scripts": [ {
    "js": [ "js/functions.js", "js/content.js" ],
    "matches": [ "http://*.mysite.com/*" ],
    "exclude_globs": [ "*board*" ],
  } ],
  "version": "0.1"
}

注意:使用“include_globs”加载 CDN 的 jQuery 不起作用。模拟 @include 是失败的,所以我不得不在扩展中包含 jQuery。

ma​​nifest.json 工作中

{
  "name": "extension name",
  "background_page": "background.html",
  "content_scripts": [ {
    "js": [ "js/jquery-1.7.1.min.js", "js/functions.js", "js/content.js" ],
    "matches": [ "http://*.mysite.com/*" ],
    "exclude_globs": [ "*board*" ],
  } ],
  "version": "0.1"
}

注意:这里我删除了在后台页面加载 jQuery。

background.html

<html>
    <head>
        <script src="js/jquery-1.7.1.min.js"></script>
        <script src="js/functions.js"></script>
    </head>
</html>

content.js

console.log('testing console');  // this works
alert('testing native JS');  // this works
$('<div id="myTestingDiv" />').prependTo('body');  // this fails

【问题讨论】:

    标签: jquery google-chrome-extension


    【解决方案1】:

    背景页面、弹出页面和内容脚本都在不同范围和文档中运行。

    在后台页面中定义的任何变量和脚本都不能在内容脚本中直接访问,反之亦然。
    另一方面,注入的内容脚本可以相互交互。

    您可以使用以下方法访问全局 (window) 对象:

    【讨论】:

    • +1。具体而言,请参阅 ContentScripts 文档中的 discussion of isolated worlds 以了解有关其工作原理的详细信息。
    • 在网页范围内执行代码见this answer。有关在注入代码中添加方法以支持chrome.* 方法的演示,请参见this diff 底部的绿色块。
    猜你喜欢
    • 1970-01-01
    • 2011-06-24
    • 1970-01-01
    • 2018-12-25
    • 2012-08-10
    • 2015-10-19
    • 2016-03-13
    • 2022-11-15
    • 2012-12-04
    相关资源
    最近更新 更多