2014-09-03 127 views
0

我正在试着学习如何制作扩展名,而且我开始非常基本。我不断收到一个错误“未捕获的ReferenceError:$没有定义”如何在Chrome扩展中使用JQuery?

这是我的manifest.json:

{ 
    "manifest_version" : 2, 
    "name": "My Extension", 
    "version": "1", 
    "description": "Testing", 
    "content_scripts": [ 
     { 
      "matches": ["http://www.google.com/*"], 
      "js": ["jquery.min.js"] 
     } 
    ], 

    "background": { 
     "scripts": ["run.js"] 
    } 
} 

jQuery的文件被正确命名和位于扩展文件夹内。这是'run.js'脚本:

$(document).ready(function() { 
    alert("document loaded"); 
}) 

我该如何解决这个问题,以便我可以正确使用JQuery?提前致谢。

回答

1

使用content_scripts/matches属性,您将限制您的jQuery只在当前URL匹配http://www.google.com/*时才加载。更改以匹配所有域:

{ 
    "manifest_version" : 2, 
    "name": "My Extension", 
    "version": "1", 
    "description": "Testing", 
    "content_scripts": [ 
     { 
      "matches": ["http://*"], 
      "js": ["jquery.min.js"] 
     } 
    ], 

    "background": { 
     "scripts": ["run.js"] 
    } 
} 

docs

Required. Specifies which pages this content script will be injected into. See Match Patterns for more details on the syntax of these strings and Match patterns and globs for information on how to exclude URLs.

OR,你可以把它添加到您现有的后台脚本:

"background": { 
    "scripts": ["jquery.min.js", "run.js"] 
} 
+0

啊,它添加到后台脚本工作。谢谢! – David 2014-09-03 07:39:25

+0

@David你可能需要这个方案,试试'http:// *'或者我的第二个建议 – CodingIntrigue 2014-09-03 07:40:17