开发者

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:

(fun开发者_运维知识库ction(){
  //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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜