views:

342

answers:

2

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.

+2  A: 

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
  }
})();
Kip
I found this contruction also, but this was before greasemonkey was able to use @require, if I unerstood it correctly. I'll give it a try.
Natrium
@Natrium: I didn't notice the `@require`. I haven't used that before, but would it just be `jQuery`, not `unsafewindow.jQuery`? If you're using `@require` I thought that defined it in the script (not on the `unsafeWindow`)
Kip
looks like @require doesn't work all that good. Now I used the good old method: http://joanpiedra.com/jquery/greasemonkey/And this works like a charm. Thank you!
Natrium
+1  A: 

@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... :)

MasterAM