user390480
user390480

Reputation: 1665

jQuery not working in Chrome Extension

This code was provided to me in another question I asked but I am getting errors right at the start. Here is the part of the code causing the problem:

// @require     http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js
// @require     https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js
// @resource    jqUI_CSS http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css
// ==/UserScript==

var cssResource = GM_getResourceText("jqUI_CSS");
GM_addStyle(cssResource);

$("#pickMe").datepicker();

The first error I get is "GM_getResourceText is not defined"

If I comment out that, and the next line, then the next error I get is "uncaught referenceerror $ is not defined." And I get that on the last line.

It's like the script is not getting the jQuery stuff from Google.

Any ideas? Thanks!

Upvotes: 0

Views: 7282

Answers (1)

Rob W
Rob W

Reputation: 348992

In Chrome, "Userscripts" are extensions. The easiest way to use external libraries is by configuring the code through a manifest file.

Download jquery.min.js, jquery-ui.min.js and jquery-ui.css, and place them in the same directory. Make sure that you resolve the paths of the images (CSS), by replacing all occurrences of url(...) with url(http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/...).

Create a manifest.json file, and add the following content:

{
    "name": "Name of your extension.",
    "version": "1.0",
    "manifest_version": 2,
    "content_scripts": [{
        "js": [
               "jquery.min.js",
               "jquery-ui.min.js",
               "mycode.js"
              ],
        "css": [ "jquery-ui.css" ],
        "matches": [ "http://similarto-at-include-in-greasemonkey.com/*" ],
        "run_at": "document_end"
    }]
}

Create a file called mycode.js (or any desired name), and add the following content:

$("#pickMe").datepicker();

You can load or pack your extension via chrome://extensions/, developer mode.

Upvotes: 4

Related Questions