为什么内容脚本不能使用后台页面上加载的jQuery?

时间:2012-03-06 15:42:48

标签: jquery google-chrome-extension

我正在构建我的第一个扩展,并且在内容脚本中使用后台页面加载的脚本时遇到问题,这使得对后台页面上加载的任何脚本真正可用于所有内容脚本产生怀疑。

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

manifest.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。

manifest.json WORKING

{
  "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

1 个答案:

答案 0 :(得分:3)

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

在“背景”页面中定义的任何变量和脚本都无法在内容脚本中直接访问,反之亦然 另一方面,注入的内容脚本可以相互交互。

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