복붙노트

[JQUERY] 어떻게 구글 크롬에서 그리스 몽키 스크립트에서 jQuery를 사용할 수 있습니까?

JQUERY

어떻게 구글 크롬에서 그리스 몽키 스크립트에서 jQuery를 사용할 수 있습니까?

해결법


  1. 1."- 에릭 Vold 사용자의 블로그 사용 jQuery를 사용자 스크립트 팁"에서

    "- 에릭 Vold 사용자의 블로그 사용 jQuery를 사용자 스크립트 팁"에서

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

  2. 2.나는 나 문서에서 함수, 코드 및 기타 스크립트를 실행 실행 도움에 에릭 Vold 사용자의 스크립트를 기반으로 몇 가지 기능을 작성했습니다. 당신은 페이지에 jQuery를 넣은 다음 글로벌 윈도우 범위에서 코드를 실행하는 데 사용할 수 있습니다.

    나는 나 문서에서 함수, 코드 및 기타 스크립트를 실행 실행 도움에 에릭 Vold 사용자의 스크립트를 기반으로 몇 가지 기능을 작성했습니다. 당신은 페이지에 jQuery를 넣은 다음 글로벌 윈도우 범위에서 코드를 실행하는 데 사용할 수 있습니다.

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

    당신은 내가 악성 뭔가를 설치하도록 사용자를 속이려는 않을거야 그 누구도 뭔가 다른 지점에 내 게시물을 편집하지 것을 신뢰하는 경우,이를 설치하려면 여기를 클릭 할 수 있습니다. 페이지를 새로 고침 당신은 내 게시물 주위에 테두리를 볼 수 있습니다.

    로드 문서에 URL에서 스크립트. 선택적으로, 콜백의 onLoad와의 OnError 제공 될 수있다.

    문서 실행한다 그것에 함수 또는 코드의 문자열을 삽입한다. 그들의 현재 범위 / 클로저를 잃고 글로벌 윈도우 범위 아래에 실행되도록 기능이 삽입되기 전에 소스 코드로 변환됩니다.

    바로 가기; 이 부하 다음 삽입하고 실행하는 functionOrCode 성공하는 경우 URL에서 스크립트.

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

  3. 3.(참) jQuery.noConflict를 호출하여 충돌의 두려움없이 사용 jQuery를. 그래서 같이 :

    (참) jQuery.noConflict를 호출하여 충돌의 두려움없이 사용 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과 그리스 몽키 스크립트로 작동하고, 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);
    }
    

  4. 4.페이지가 이미 jQuery를 가지고 있다면, 바로이 템플릿을 따르십시오 :

    페이지가 이미 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);
    

  5. 5.간단한 방법은 필요한 키워드를 사용하고 있습니다 :

    간단한 방법은 필요한 키워드를 사용하고 있습니다 :

    // @require     http://code.jquery.com/jquery-latest.js
    

  6. 6.그 스크립트는 실제로 특권 기능을 사용하지 않는 크롬 스크립트 (GM_ * 기능 등)에 대한 jQuery를의 전체 복사본을 포함하여 주위에 얻을 수있는 정말 쉬운 방법이 ...

    그 스크립트는 실제로 특권 기능을 사용하지 않는 크롬 스크립트 (GM_ * 기능 등)에 대한 jQuery를의 전체 복사본을 포함하여 주위에 얻을 수있는 정말 쉬운 방법이 ...

    단순히 페이지 DOM에 스크립트 자체를 삽입하고 실행! 가장 좋은 부분은 당신이 모두 동일한 스크립트를 사용할 수 있도록이 기술은, 파이어 폭스 + 그리스 몽키에 그냥 잘 작동한다는 것입니다 :

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

    (변명 그가 여기 이동하지 않았고, 내가 메타 게시물을 삭제해야하기 때문에 meta.stackoverflow에 Shog9에서 도난 ..)


  7. 7.또한, 크롬 확장 프로그램에 jQuery를 사용하여 스크립트를 포장 할 수있다. 구글 크롬 컨텐츠 스크립트를 참조하십시오.

    또한, 크롬 확장 프로그램에 jQuery를 사용하여 스크립트를 포장 할 수있다. 구글 크롬 컨텐츠 스크립트를 참조하십시오.

    크롬 확장 프로그램, 그리스 몽키 스크립트와는 달리, 캔 자동 업데이트 자체.


  8. 8.쉽게 솔루션 : 컷 +는 사용자 스크립트의 상단에 jquery.min.js의 내용을 붙여 넣습니다. 끝난.

    쉽게 솔루션 : 컷 +는 사용자 스크립트의 상단에 jquery.min.js의 내용을 붙여 넣습니다. 끝난.

    나는 추천 답변 다양한 문제를 발견했다. addJQuery () 솔루션은 대부분의 페이지에서 작동하지만, 많은에 버그가 있습니다. 당신은 문제가 발생하는 경우 당신의 스크립트에 JQuery와 내용을 붙여 + 복사합니다.


  9. 9.당신이 당신의 GM 스크립트 람에 document.defaultView.jQuery에 의존하지 수 있는지 궁금해 :

    당신이 당신의 GM 스크립트 람에 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($);
    }
    

  10. 10.또 다른 방법은 수동으로로드 jQuery를 귀하의 스크립트를 수정하는 것입니다. http://joanpiedra.com/jquery/greasemonkey/에서 예 :

    또 다른 방법은 수동으로로드 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
    }
    

    편집 : DRATS! 테스트 후에는 Google 크롬 userscripts / 실제 웹 페이지에서 별도의 범위 / 과정에서 확장을 실행하기 때문에이 코드가 작동하지 않습니다 나타납니다. 당신은 XMLHttpRequest를하고 평가를 사용하여 jQuery 코드를 다운로드 할 수 있습니다,하지만 당신은 액세스 제어 - 허용 - 원산지를 사용하여 간 리소스 공유를 허용하는 서버에 코드를 호스팅해야합니다 : * 헤더입니다. jQuery로 현재 CDN 서비스의 슬프게도 아무도는이 기능을 지원하지 않습니다.


  11. 11.당신이 상상할 수있는 간단하게 크롬 콘솔에 포함 jQuery를에 완벽한 확장. jQuery를 이미 페이지에 임베디드 된 경우이 확장은 indocates.

    당신이 상상할 수있는 간단하게 크롬 콘솔에 포함 jQuery를에 완벽한 확장. jQuery를 이미 페이지에 임베디드 된 경우이 확장은 indocates.

    당신이 원하는 모든 페이지에 삽입 jQuery를 사용이 확장. 그것은 (당신은 "Ctrl 키 + 시프트 + J"가 크롬 콘솔을 호출 할 수 있습니다) 콘솔 쉘에서 jQuery를 사용할 수 있습니다.

    하려면 확장 버튼을 선택 탭을 클릭에 jQuery를 포함.

    확장에 LINK : https://chrome.google.com/extensions/detail/gbmifchmngifmadobkcpijhhldeeelkc

  12. from https://stackoverflow.com/questions/2246901/how-can-i-use-jquery-in-greasemonkey-scripts-in-google-chrome by cc-by-sa and MIT license