简体   繁体   English

如何在Chrome扩展程序中使用JQuery?

[英]How can I use JQuery in a Chrome extension?

I'm trying to learn how to make extensions, and I'm starting off very basic. 我正在尝试学习如何进行扩展,并且从最基本的开始。 I keep getting an error "Uncaught ReferenceError: $ is not defined" 我不断收到错误消息“未捕获的ReferenceError:未定义$”

This is my manifest.json: 这是我的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"]
    }
}

The JQuery file is properly named and located inside of the extension folder. JQuery文件已正确命名,并位于扩展文件夹内。 This is the 'run.js' script: 这是“ run.js”脚本:

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

How can I fix this so that I can properly use JQuery? 如何解决此问题,以便可以正确使用JQuery? Thanks in advance. 提前致谢。

Using the content_scripts/matches property, you're limiting your jQuery to only load if the current URL matches http://www.google.com/* . 使用content_scripts/matches属性,您可以限制jQuery仅在当前URL匹配http://www.google.com/*加载。 Change it to match all domains: 对其进行更改以匹配所有域:

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

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

From the 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. 有关这些字符串的语法的更多详细信息,请参见“匹配模式”,有关如何排除URL的信息,请参见“匹配模式和全局”。

OR , you can add it to your existing background scripts: ,您可以将其添加到现有的后台脚本中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM