簡體   English   中英

如何在Greasemonkey腳本中包含遠程javascript文件?

[英]How do I include a remote javascript file in a Greasemonkey script?

我正在嘗試編寫一個Greasemonkey腳本,並希望使用jQuery庫來執行此操作,但我不太確定如何從Web地址中包含jQuery以進行滾動。

我如何將jQuery(來自Google的Web服務器)包含在greasemonkey腳本中,以便我可以去:

$(document).ready(function(){
  // Greasemonkey stuff here
});

我更願意從這個來源獲得它:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>

更新:感謝您的幫助,答案非常豐富。 不過,我確實更多地利用了我的GoogleFu並遇到了這個解決方案http ://joanpiedra.com/jquery/greasemonkey/

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

最近版本的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==

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

感謝Paul Tarjan指出這一點。 請參閱jQuery論壇帖子

還要注意這些@require語義

在安裝用戶腳本時,Greasemonkey將下載並保留遠程文件的本地緩存副本,該副本幾乎可以立即讀取。 緩存的副本與安裝的用戶腳本保存在同一文件夾中。 不監視遠程文件的更改。

請注意,在撰寫本答案時,此@require標記僅在安裝時讀取。 如果編輯現有用戶腳本以添加此標記,則將忽略該標記。 您需要卸載並重新安裝用戶腳本才能獲取更改。

這里

// ==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"); 
                } 
            } 
        }); 
} 

它運行良好,但您可能希望限制它運行的站點或在您自己的站點上托管jQuery js文件,以免竊取他們的帶寬。

您可以嘗試動態創建腳本元素:

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

腳本加載時你可能需要延遲一點(setTimeout?)

根據克里斯的回答 ,我調整了自己的需求,如下所示。

// ==UserScript==
// @description require http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.jss
// @name         Baidu Mask
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://www.ibm.com/developerworks/cn/opensource/os-cn-greasemonkey/index.html
// @match        *://www.baidu.com/*
// @match        *://baike.baidu.com/*
// @match        *://zhidao.baidu.com/*
// @match        *://www.weather.com.cn/*
// @grant        none
// ==/UserScript==

(function () {
    'use strict';

    // Your code here...

    var $j;

    function GM_wait() {
        if (typeof jQuery === 'undefined') {
            window.setTimeout(GM_wait, 100);
        }
        else {
            $j = jQuery.noConflict();
            doJob();
        }
    }

    function loadJquery() {
        // Check if jQuery's loaded

        if (typeof jQuery === 'undefined') {
            // Add jQuery
            var GM_JQ = document.createElement('script');
            GM_JQ.src = 'https://code.jquery.com/jquery-1.12.4.min.js';
            GM_JQ.type = 'text/javascript';
            GM_JQ.id = 'jquery-lyz';
            document.getElementsByTagName('head')[0].appendChild(GM_JQ);
            GM_wait();
        } else {
            doJob();
        }
    }

    loadJquery();


    function doJob() {
        if (typeof $j === 'undefined') {
            $j = $;
        }

        var url_arr = [
            {'name': "baidu", 'value': "www.baidu.com"},
            {'name': "baike", 'value': "baike.baidu.com"},
            {'name': "zhidao", 'value': "zhidao.baidu.com"},
            {'name': "weather", 'value': "http://www.weather.com.cn"},
        ];
        var url = location.href;
        var siteObj = {};
        $j(url_arr).each(function (i, item) {
            if (url.indexOf(item.value) > -1) {
                siteObj = item;
                return false;
            }
        });

        var delay_arr = [];
        var timerCount = 1;

        function hideTimer() {
            timerCount++;
            if (timerCount > 20) {
                return;
            }
            delay_arr = $j.grep(delay_arr, function (_selector, i) {
                var $ele = $j(_selector);
                var visible = $ele.is(':visible');
                console.log($ele, visible);
                if (visible) {
                    $ele.hide();
                    return false;
                }


                return true; // keep the element in the array
            });
            if (delay_arr.length > 0) {
                setTimeout(hideTimer, 500);
            }
        }

        setTimeout(hideTimer, 500);
        var $frms;
        switch (siteObj.name) {
            case 'baidu':
                $j('#content_right').hide();
                break;
            case 'baike':
                $j('.topA, .lemmaWgt-promotion-slide, .union-content, .right-ad, .lemmaWgt-promotion-vbaike, .nav-menu').hide();
                delay_arr.push('#side_box_unionAd');
                break;
            case 'zhidao':
                $j('.widget-new-graphic, #union-asplu, .jump-top-box').hide();
                delay_arr.push('.wgt-daily');
                delay_arr.push('.shop-entrance');
                delay_arr.push('.cms-slide');
                delay_arr.push('.nav-menu');
                $frms = $j('iframe');
                $frms.hide();
                break;
            case 'weather':
                $j('.right, .hdImgs, .tq_zx, #di_tan, #zu_dui').hide();
                //delay_arr.push('.wgt-daily');
                $frms = $j('iframe');
                $frms.hide();
                break;
        }
    }

})();

我的腳本需要在不同的站點上工作,有些包含jquery而有些則沒有,所以我必須測試。 “需要”的方式在這里不起作用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM