Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is $ undefined when I try to use jQuery in GreaseMonkey?

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.

like image 745
Natrium Avatar asked Mar 24 '10 13:03

Natrium


3 Answers

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
  }
})();
like image 128
Kip Avatar answered Oct 05 '22 10:10

Kip


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

like image 30
MasterAM Avatar answered Oct 05 '22 12:10

MasterAM


newer greasemonkey need to add // @grant none to use // @require

like image 20
uingtea Avatar answered Oct 05 '22 10:10

uingtea