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

匿名 (未验证) 提交于 2019-12-03 08:46:08

问题:

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.

回答1:

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   } })(); 


回答2:

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



回答3:

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!