Google Chrome の Greasemonkey スクリプトで jQuery を使用するにはどうすればよいですか?

StackOverflow https://stackoverflow.com/questions/2246901

質問

ご存知の方もいるかもしれませんが、Google Chrome では Greasemonkey スクリプトに厳しい制限が設けられています。

クロムはサポートしていません @require, @resource, unsafeWindow, GM_registerMenuCommand, GM_setValue, 、 または GM_getValue.

require がなければ、Google Chrome の Greasemonkey スクリプトに jQuery ライブラリを含める方法が見つかりません。

この件に関して誰かアドバイスはありますか?

役に立ちましたか?

解決

<のhref = "からhttp://web.archive.org/web/20130804120117/http://erikvold.com/blog/index.cfm/2010/6/14/using-jquery-with-a -user-スクリプト」relが= "noreferrer"> "ユーザースクリプトのヒント:jQueryの使い方 - エリックVOLDのブログを" する

// ==UserScript==
// @name         jQuery For Chrome (A Cross Browser Example)
// @namespace    jQueryForChromeExample
// @include      *
// @author       Erik Vergobbi Vold & Tyler G. Hicks-Wright
// @description  This userscript is meant to be an example on how to use jQuery in a userscript on Google Chrome.
// ==/UserScript==

// a function that loads jQuery and calls a callback function when jQuery has finished loading
function addJQuery(callback) {
  var script = document.createElement("script");
  script.setAttribute("src", "//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js");
  script.addEventListener('load', function() {
    var script = document.createElement("script");
    script.textContent = "window.jQ=jQuery.noConflict(true);(" + callback.toString() + ")();";
    document.body.appendChild(script);
  }, false);
  document.body.appendChild(script);
}

// the guts of this userscript
function main() {
  // Note, jQ replaces $ to avoid conflicts.
  alert("There are " + jQ('a').length + " links on this page.");
}

// load jQuery and execute the main function
addJQuery(main);

他のヒント

私は<のhref =「http://erikvold.com/blog/index.cfm/2010/6/14/using-jquery-with-a-user-script」RELに基づいていくつかの関数を書かれています=「noreferrer」>エリックVOLDのスクリプトは、私は、ドキュメント内の関数、コードや他のスクリプトを実行して実行を支援するを。あなたは、ページにjQueryのをロードし、グローバルwindowスコープの下でコードを実行するためにそれらを使用することができます。

使用例

// ==UserScript==
// @name           Example from http://stackoverflow.com/q/6834930
// @version        1.3
// @namespace      http://stackoverflow.com/q/6834930
// @description    An example, adding a border to a post on Stack Overflow.
// @include        http://stackoverflow.com/questions/2246901/*
// ==/UserScript==

var load,execute,loadAndExecute;load=function(a,b,c){var d;d=document.createElement("script"),d.setAttribute("src",a),b!=null&&d.addEventListener("load",b),c!=null&&d.addEventListener("error",c),document.body.appendChild(d);return d},execute=function(a){var b,c;typeof a=="function"?b="("+a+")();":b=a,c=document.createElement("script"),c.textContent=b,document.body.appendChild(c);return c},loadAndExecute=function(a,b){return load(a,function(){return execute(b)})};

loadAndExecute("//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js", function() {
    $("#answer-6834930").css("border", ".5em solid black");
});

あなたは、それをインストールするには、ここをクリックすることができますあなたがいることを信頼している場合、私は悪質な何かをインストールするにして誰もが何か他のものを指すように私のポストを編集していないことを、あなたのトリックしようとしていませんよ。ページを再読み込みして、あなたは私のポストの周囲に境界線が表示されるはずです。

機能

load(url, onLoad, onError)

は、ドキュメントにurlでスクリプトをロードします。必要に応じて、コールバックはonLoadonErrorために提供されてもよい。

execute(functionOrCode)

は、ドキュメントに関数またはコードの文字列を挿入し、それを実行します。機能が挿入される前に、ソースコードに変換されるので、彼らの現在のスコープ/クロージャを失い、グローバルwindowスコープの下に実行されます。

loadAndExecute(url, functionOrCode)

ショートカット。成功した場合、これはurlからスクリプトをロードし、その後、functionOrCodeを挿入して実行します。

コード

function load(url, onLoad, onError) {
    e = document.createElement("script");
    e.setAttribute("src", url);

    if (onLoad != null) { e.addEventListener("load", onLoad); }
    if (onError != null) { e.addEventListener("error", onError); }

    document.body.appendChild(e);

    return e;
}

function execute(functionOrCode) {
    if (typeof functionOrCode === "function") {
        code = "(" + functionOrCode + ")();";
    } else {
        code = functionOrCode;
    }

    e = document.createElement("script");
    e.textContent = code;

    document.body.appendChild(e);

    return e;
}

function loadAndExecute(url, functionOrCode) {
    load(url, function() { execute(functionOrCode); });
}

jQuery.noConflict(true)を呼び出すことによって、の紛争の恐れなしののjQueryを使用してください。これと同様ます:

function GM_main ($) {
    alert ('jQuery is installed with no conflicts! The version is: ' + $.fn.jquery);
}

add_jQuery (GM_main, "1.7.2");

function add_jQuery (callbackFn, jqVersion) {
    jqVersion       = jqVersion || "1.7.2";
    var D           = document;
    var targ        = D.getElementsByTagName ('head')[0] || D.body || D.documentElement;
    var scriptNode  = D.createElement ('script');
    scriptNode.src  = 'http://ajax.googleapis.com/ajax/libs/jquery/'
                    + jqVersion
                    + '/jquery.min.js'
                    ;
    scriptNode.addEventListener ("load", function () {
        var scriptNode          = D.createElement ("script");
        scriptNode.textContent  =
            'var gm_jQuery  = jQuery.noConflict (true);\n'
            + '(' + callbackFn.toString () + ')(gm_jQuery);'
        ;
        targ.appendChild (scriptNode);
    }, false);
    targ.appendChild (scriptNode);
}
<時間> <時間>

しかし、ときにすることができのクロスブラウザスクリプトの場合は、なぜ、jQueryのの素敵な、速い、ローカルコピーを利用しませんか?

クロームuserscriptとGreasemonkeyのスクリプトとして、以下の作品を、そしてプラットフォームがサポートしている場合、それは、jQueryのの素敵なローカル@requireのコピーを使用します。

// ==UserScript==
// @name     _Smart, cross-browser jquery-using script
// @include  http://YOUR_SERVER.COM/YOUR_PATH/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @grant    GM_info
// ==/UserScript==

function GM_main ($) {
    alert ('jQuery is installed with no conflicts! The version is: ' + $.fn.jquery);
}

if (typeof jQuery === "function") {
    console.log ("Running with local copy of jQuery!");
    GM_main (jQuery);
}
else {
    console.log ("fetching jQuery from some 3rd-party server.");
    add_jQuery (GM_main, "1.7.2");
}

function add_jQuery (callbackFn, jqVersion) {
    var jqVersion   = jqVersion || "1.7.2";
    var D           = document;
    var targ        = D.getElementsByTagName ('head')[0] || D.body || D.documentElement;
    var scriptNode  = D.createElement ('script');
    scriptNode.src  = 'http://ajax.googleapis.com/ajax/libs/jquery/'
                    + jqVersion
                    + '/jquery.min.js'
                    ;
    scriptNode.addEventListener ("load", function () {
        var scriptNode          = D.createElement ("script");
        scriptNode.textContent  =
            'var gm_jQuery  = jQuery.noConflict (true);\n'
            + '(' + callbackFn.toString () + ')(gm_jQuery);'
        ;
        targ.appendChild (scriptNode);
    }, false);
    targ.appendChild (scriptNode);
}

ページがすでにjQueryのを持っている場合は、ちょうどこのテンプレートは、次のとおりです。

// ==UserScript==
// @name          My Script
// @namespace     my-script
// @description   Blah
// @version       1.0
// @include       http://site.com/*
// @author        Me
// ==/UserScript==

var main = function () {

    // use $ or jQuery here, however the page is using it

};

// Inject our main script
var script = document.createElement('script');
script.type = "text/javascript";
script.textContent = '(' + main.toString() + ')();';
document.body.appendChild(script);

簡単な方法は、requiredキーワードを使用しています:

// @require     http://code.jquery.com/jquery-latest.js
のこれらのスクリプトは、実際に任意の特権機能を使用しないの(GM_ *関数、など)...

単にページのDOMにスクリプト自体を挿入し、実行!最良の部分は、この技術は、Firefox + Greasemonkeyの上で全く同じように動作することであるので、あなたは両方に同じスクリプトを使用することができます:

var script = document.createElement("script");
script.type = "text/javascript";
script.textContent = "(" + threadComments.toString() + ")(jQuery)";
document.body.appendChild(script);

function threadComments($) {
    // taken from kip's http://userscripts-mirror.org/scripts/review/62163
    var goodletters = Array('\u00c0','\u00c1','\u00c2','\u00c3','\u00c4','\u00c5','\u00c6','\u00c7'
                             ,'\u00c8','\u00c9','\u00ca','\u00cb','\u00cc','\u00cd','\u00ce','\u00cf'
                                      ,'\u00d1','\u00d2','\u00d3','\u00d4','\u00d5','\u00d6'         
                             ,'\u00d8','\u00d9','\u00da','\u00db','\u00dc','\u00dd'                  
                             ,'\u00e0','\u00e1','\u00e2','\u00e3','\u00e4','\u00e5','\u00e6','\u00e7'
                             ,'\u00e8','\u00e9','\u00ea','\u00eb','\u00ec','\u00ed','\u00ee','\u00ef'
                                      ,'\u00f1','\u00f2','\u00f3','\u00f4','\u00f5','\u00f6'         
                             ,'\u00f8','\u00f9','\u00fa','\u00fb','\u00fc','\u00fd'         ,'\u00ff').join('');

    // from Benjamin Dumke's http://userscripts-mirror.org/scripts/review/68252
    function goodify(s)
      {
         good = new RegExp("^[" + goodletters + "\\w]{3}");
         bad = new RegExp("[^" + goodletters + "\\w]");
         original = s;
         while (s.length >3 && !s.match(good)) {
            s = s.replace(bad, "");
            }
         if (!s.match(good))
         {
           // failed, so we might as well use the original
           s = original;
         }
         return s;
      }  

    in_reply_to = {};


    function who(c, other_way) {


        if (other_way)
        {
            // this is closer to the real @-reply heuristics
            m = /@(\S+)/.exec(c);
        }
        else
        {
            m = /@([^ .:!?,()[\]{}]+)/.exec(c);
        }
        if (!m) {return}
        if (other_way) {return goodify(m[1]).toLowerCase().slice(0,3);}
        else {return m[1].toLowerCase().slice(0,3);}
    }

    function matcher(user, other_way) {
        if (other_way)
        {
            return function () {
                return goodify($(this).find(".comment-user").text()).toLowerCase().slice(0,3) == user
                }
        }
        else
        {
            return function () {
                return $(this).find(".comment-user").text().toLowerCase().slice(0,3) == user
                }
        }
    }

    function replyfilter(id) {
        return function() {
            return in_reply_to[$(this).attr("id")] == id;
        }
    }

    function find_reference() {
        comment_text = $(this).find(".comment-text").text();
        if (who(comment_text))
        {
            fil = matcher(who(comment_text));
            all = $(this).prevAll("tr.comment").filter(fil);
            if (all.length == 0)
            {
                // no name matched, let's try harder
                fil = matcher(who(comment_text, true), true);
                all = $(this).prevAll("tr.comment").filter(fil);
                if (all.length == 0) {return}
            }
            reference_id = all.eq(0).attr("id");
            in_reply_to[$(this).attr("id")] = reference_id;
        }
    }


    // How far may comments be indented?
    // Note that MAX_NESTING = 3 means there are
    // up to *four* levels (including top-level)
    MAX_NESTING = 3

    // How many pixels of indentation per level?
    INDENT = 30

    function indenter(parent) {

        for (var i = MAX_NESTING; i > 0; i--)
        {
            if (parent.hasClass("threading-" + (i-1)) || (i == MAX_NESTING && parent.hasClass("threading-" + i)))
            {
                return function() {
                    $(this).addClass("threading-" + i).find(".comment-text").css({"padding-left": INDENT*i});
                }
            }
        }

        return function() {
            $(this).addClass("threading-1").find(".comment-text").css({"padding-left": INDENT});
        }

    }

    function do_threading(){
        id = $(this).attr("id");
        replies = $(this).nextAll("tr.comment").filter(replyfilter(id));
        ind = indenter($(this));
        replies.each(ind);
        replies.insertAfter(this);
    }

    function go() {
        $("tr.comment").each(find_reference);
        $("tr.comment").each(do_threading);
    }

    $.ajaxSetup({complete: go});
    go();
}

(unapologetically彼はそれをここに移動していなかったので、meta.stackoverflow上Shog9から盗まれた、と私はメタ投稿を削除する必要が...)

また、あなたはChromeの拡張機能にjQueryを使ってスクリプトを詰めることができました。 Google Chromeのコンテンツスクリプトを参照してください。

のGreasemonkeyスクリプトとは異なり、Chromeの拡張機能は、自身を自動更新することができます。

簡単ソリューション:カット+ユーザースクリプトの先頭にjquery.min.jsの内容を貼り付けます。完了。

私はお勧めの答えと様々な問題を発見しました。 addJQuery()ソリューションは、ほとんどのページで動作しますが、多くのバグがあります。あなたが問題に遭遇した場合は、単に+スクリプトにjqueryの内容をコピー&ペーストます。

あなたはGMスクリプトALAにdocument.defaultView.jQueryに頼ることができなかった場合、私は疑問に思う:

if (document.defaultView.jQuery) {
  jQueryLoaded(document.defaultView.jQuery);
} else {
  var jq = document.createElement('script');
  jq.src = 'http://jquery.com/src/jquery-latest.js';
  jq.type = 'text/javascript';
  document.getElementsByTagName('head')[0].appendChild(jq);
  (function() { 
    if (document.defaultView.jQuery) jQueryLoaded(document.defaultView.jQuery);
    else setTimeout(arguments.callee, 100);
  })();
}

function jQueryLoaded($) {
  console.dir($);
}

もう 1 つの方法は、jQuery を手動でロードするようにスクリプトを変更することです。例から http://joanpiedra.com/jquery/greasemonkey/:

// 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
}

編集:ドラッツ! テストの結果、Google Chrome は実際の Web ページとは別のスコープ/プロセスでユーザー スクリプト/拡張機能を実行するため、このコードは機能しないことがわかりました。XmlhttpRequest を使用して jQuery コードをダウンロードし、それを評価することはできますが、コードをサーバー上でホストする必要があります。 クロスオリジンリソース共有 を使用して Access-Control-Allow-Origin: * ヘッダ。悲しいことに 現在の CDN はどれもありません jQuery を使用するとこれがサポートされます。

パーフェクト拡張子は、あなたが想像できるような単純なクロームコンソールへのjQueryを埋め込むことができます。 jQueryのは、すでにページに埋め込まれている場合、この拡張機能もindocatesます。

この拡張機能は、あなたが望む任意のページへのjQueryを埋め込むために使用しました。それは(あなたが「Ctrlキー+ Shiftキー+ J」でクロームコンソールを呼び出すことができます)、コンソールシェルでのjQueryを使用することができます。

拡張子]ボタンを選択したタブをクリックへのjQueryを埋め込むことができます。

拡張子を

LINK: https://chrome.google.com/extensions/detail/gbmifchmngifmadobkcpijhhldeeelkc

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top