如何在Greasemonkey脚本中包含远程javascript文件?

tes*_*ter 22 javascript jquery greasemonkey

我正在尝试编写一个Greasemonkey脚本,并希望使用jQuery库来执行此操作,但我不太确定如何从Web地址中包含jQuery以进行滚动.

如何将jQuery(来自Google的Web服务器)包含在greasemonkey脚本中,以便我可以:

$(document).ready(function(){
  // Greasemonkey stuff here
});
Run Code Online (Sandbox Code Playgroud)

我更愿意从这个来源获得它:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>
Run Code Online (Sandbox Code Playgroud)

更新:感谢您的帮助,答案非常丰富.不过,我确实更多地利用了我的GoogleFu并遇到了这个解决方案:http://joanpiedra.com/jquery/greasemonkey/

像魅力一样工作..只需更新谷歌的托管版jQuery即可完成.

Che*_*oft 39

最近版本的greasemonkey中推荐的方法是使用@require注释标记.

例如

// ==UserScript==
// @name          Hello jQuery
// @namespace     http://www.example.com/
// @description   jQuery test script
// @include       *
// @require       http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js
// ==/UserScript==
Run Code Online (Sandbox Code Playgroud)

但是......请注意,jQuery 1.4.1和1.4.2与此方法不兼容

感谢Paul Tarjan指出这一点.请参阅jQuery论坛帖子.

还要注意这些@require语义

在安装用户脚本时,Greasemonkey将下载并保留远程文件的本地缓存副本,该副本几乎可以立即读取.缓存的副本与安装的用户脚本保存在同一文件夹中.不监视远程文件的更改.

请注意,在撰写本答案时,此@require标记仅在安装时读取.如果编辑现有用户脚本以添加此标记,则将忽略该标记.您需要卸载并重新安装用户脚本才能获取更改.

  • 小心,这不适用于1.4.1或1.4.2:http://forum.jquery.com/topic/importing-jquery-1-4-1-into-greasemonkey-scripts-generates-an-error (3认同)

Chr*_*ett 11

这里:

// ==UserScript== 
// @name           jQueryTest 
// @namespace      http://www.example.com/
// @include        * 
// ==/UserScript== 

// Add jQuery 
var GM_JQ = document.createElement('script'); 
GM_JQ.src = 'http://jquery.com/src/jquery-latest.js';
GM_JQ.type = 'text/javascript'; 
document.getElementsByTagName('head')[0].appendChild(GM_JQ); 

// Check if jQuery's loaded 
function GM_wait() { 
    if(typeof unsafeWindow.jQuery == 'undefined') 
{ window.setTimeout(GM_wait,100); } 
        else { $ = unsafeWindow.jQuery; letsJQuery(); } 
} 
GM_wait(); 

// All your GM code must be inside this function 
function letsJQuery() { 

    alert($); // check if the dollar (jquery) function works 
    // the next call fails 
    $("<div id='example' class='flora' title='This is my title'>I'm in 
a dialog!</div>").dialog({ 
            buttons: { 
                "Ok": function() { 
                    alert("Ok"); 
                }, 
                "Cancel": function() { 
                    $(this).dialog("close"); 
                } 
            } 
        }); 
} 
Run Code Online (Sandbox Code Playgroud)

它运行良好,但您可能希望限制它运行的站点或在您自己的站点上托管jQuery js文件,以免窃取他们的带宽.


Emm*_*ett 6

您可以尝试动态创建脚本元素:

var script = document.createElement("script");
script.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js";
document.getElementsByTagName("head")[0].appendChild(script);
Run Code Online (Sandbox Code Playgroud)

您可能需要在脚本加载时延迟一段时间(setTimeout?)