David
David

Reputation: 733

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"

This is my 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. This is the 'run.js' script:

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

How can I fix this so that I can properly use JQuery? Thanks in advance.

Upvotes: 0

Views: 39

Answers (1)

CodingIntrigue
CodingIntrigue

Reputation: 78525

Using the content_scripts/matches property, you're limiting your jQuery to only load if the current URL matches 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.

OR, you can add it to your existing background scripts:

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

Upvotes: 1

Related Questions