问题
I'm trying to add jQuery using Greasemonkey's @require
/ @include
method, but it doesn't work. The following error shows up:
Uncaught ReferenceError: $ is not defined (repeated 10 times)
This is my sample code:
// ==UserScript==
// @description Bored, really bored.
// @name MatteoSample
// @namespace MatteoSampleNamespace
// @include *
// @include http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js
// ==/UserScript==
$(document).slideUp();
How can I fix it?
回答1:
@ic
is not a valid meta-rule, so it's ignored.
Use @require if you want to load jQuery in your user script.
// ==UserScript==
// @name Foo
// @namespace Bar
// @include *
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js
// ==/UserScript==
EDIT: In the comments, you said that you're using Chrome. Chrome does not support the @require
rule. See also:
- GreaseSpot Wiki: Cross-browser userscripting
- Stack Overflow: Why doesn't jQuery work in Chrome user scripts (Greasemonkey)?
- Stack Overflow: How can I use jQuery in Greasemonkey scripts in Google Chrome?
If you want full Greasemonkey support in Chrome, use Tampermonkey.
Clearing up confusion about User scripts in Chrome
Chrome does not natively support GreaseMonkey. Whenever a .user.js
file is loaded, it's converted to a Chrome extension in form of a Content script.
For more information on User scripts in Chrome, see this documentation.
The User script is literally copied into the extension's directory:
// ==UserScript==
// @name Foo
// @namespace Bar
// @include *
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js
// ==/UserScript==
alert(typeof $)
A manifest.json file is created, based on the meta block. When the User script contains a @include
rule, its matches
rule will contain https://*/*
and http://*/*
, because of the too loose @include
rule.
The contents of the generated manifest.json
looks like:
{
"content_scripts": [ {
"exclude_globs": [ ],
"include_globs": [ "*" ],
"js": [ "script.js" ],
"matches": [ "http://*/*", "https://*/*" ],
"run_at": "document_idle"
} ],
"converted_from_user_script": true,
"description": "",
"key": "+.... some key ...=",
"name": "Foo",
"version": "1.0"
}
回答2:
chrome doesn't support greasemonkey scripts, rather, specific greasemonkey commands (@require, GM_ etc)
to get that stuff working, install chrome addon "TamperMonkey"
来源:https://stackoverflow.com/questions/9791489/greasemonkey-require-does-not-work-in-chrome