将jQuery加载到chrome扩展中

the*_*ius 16 jquery manifest google-chrome-extension

我正在尝试进入Chrome扩展程序的神奇世界.现在我已经构建了我的清单,试图加载jquery.

{
    "name": "Test Extension",
    "version": "0.1",
    "manifest_version": 2,
    "description": "First try",
    "options_page": "options.html",
    "content_scripts": [{
        "matches": ["chrome-extension://*/*"],
        "js": ["jquery.js", "popup.js"],
        "run_at": "document_end"
    }],
    "browser_action": {
        "default_icon": "icon.png",
        "default_popup": "popup.html",
        "default_title": "Click me!"
    }
}
Run Code Online (Sandbox Code Playgroud)

实际上尝试重新加载扩展名告诉我"匹配"与有效架构不匹配.

但那还不是全部.为了克服它,我尝试只更改"匹配"值*://*/*并重新加载.好吧,扩展似乎加载正确,但似乎没有加载jquery由于我可以从popup.js得到的错误,只是告诉我

未捕获的ReferenceError:$未定义

实际上HTML只是:

<!doctype html>
<html>
<head>
    <title>Test Extension</title>
    <link rel="stylesheet" style="text/css" src="style.css">
</head>
<body>
    <div id="test"></div>
</body>
</html>
<script type="text/javascript" src="popup.js"></script>
Run Code Online (Sandbox Code Playgroud)

popup.js代码就是这样做的:

$("#test").html("Foo!");
Run Code Online (Sandbox Code Playgroud)

Rob*_*b W 17

内容脚本永远不会在扩展的上下文中运行.在浏览器操作弹出窗口中加载脚本的正确方法是将其包含在代码中.让你的清单文件是:

{
    "name": "Test Extension",
    "version": "0.1",
    "manifest_version": 2,
    "options_page": "options.html",
    "browser_action": {
        "default_icon": "icon.png",
        "default_popup": "popup.html",
        "default_title": "Click me!"
    }
}
Run Code Online (Sandbox Code Playgroud)

而且popup.html:

...
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="popup.js"></script>
Run Code Online (Sandbox Code Playgroud)

  • 改变你的建议,给我以下错误:拒绝执行内联脚本,因为它违反了以下`内容安全策略指令:"script-src'self'chrome-extension-resource:". (2认同)
  • @theCrius你在头上包括`popup.js`.该脚本立即执行,但`<body>`甚至还不存在.要解决这个特定问题,请将代码包装在domready事件处理程序中:`$(function(){$('#text').html('Foo!');});` - 请参阅http:// api. jquery.com/ready/ (2认同)