I'm totally new to GreaseMonkey, but I'm trying to make a little script.
// ==UserScript==
// @require http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js
// ==/UserScript==
(function() {
$ = unsafeWindow.jQuery;
alert($); // this gives 'undefined'
}());
Why does the alert give undefined
and how to fix this?
UPDATE
I tried this:
(function(){
//boilerplate greasemonkey to wait until jQuery is defined...
function GM_wait()
{
alert('ok');
if(typeof unsafeWindow.jQuery == 'undefined')
window.setTimeout(GM_wait,100);
else
unsafeWindow.jQuery(function() { letsJQuery(unsafeWindow.jQuery); });
}
GM_wait();
function letsJQuery($)
{
alert($);
}
})();
but this gave me an infinite loop of ok-alerts. Seems like jQuery doesn't get loaded at all.
Edit: Could it be this?
Perhaps you don't have a recent enough version of Greasemonkey. It was version 0.8 that added @require. Also, remember that @require is only processed when the script is first installed. If you change the list of required scripts, you need to uninstall it and reinstall it; Greasemonkey downloads the required script once at installation and uses a cached copy thereafter.
The GM script could be executing before the page is ready (i.e. before jQuery has initialized). I use this code in my Greasemonkey scripts in order to use jQuery:
(function(){
//boilerplate greasemonkey to wait until jQuery is defined...
function GM_wait()
{
if(typeof unsafeWindow.jQuery == 'undefined')
window.setTimeout(GM_wait,100);
else
unsafeWindow.jQuery(function() { letsJQuery(unsafeWindow.jQuery); });
}
GM_wait();
function letsJQuery($)
{
//whatever
}
})();
@require
is meant to perform a one-time resource download.
At first install, the resource is downloaded and placed within the script's folder.
The required script then executes prior to the userscript.
It is run under the same scope as the user script, not under unsafeWindow
.
If you are writing the script yourself, then it would not get the resource until you actually install it (or edit the GM xml files to recognize the resource and plant the file in the script's dir, within firefox's user profile directory).
If you choose the (simpler) uninstall\reinstall method, don't forget to backup your userscript... :)
newer greasemonkey need to add // @grant none
to use // @require
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With