0

(Chromeで使用するための)ユーザースクリプトをまとめようとしていますが、壁にぶつかり続けています。私の最初の目標は、ScottReedのgSearchjQueryプラグインをスクリプトを介して任意のページで機能させることです。

これが私がスニペットと例を押し込んで持っているスクリプトです、私はあちこちで一緒に見つけます:

これで発生するエラーは「Uncaught TypeError: Cannot read property 'WebSearch' of undefined」です。

// ==UserScript==
// @name           Example
// @version        1.2
// @namespace      
// @description    
// @include *
// ==/UserScript==

function addScripts(callback) {
  var script = document.createElement("script");
  script.setAttribute("src", "http://google.com/jsapi");
  script.addEventListener('load', function() {
    var script = document.createElement("script");
    script.textContent = "(" + callback.toString() + ")();";
    document.body.appendChild(script);
  }, false);
  document.body.appendChild(script);

  var script = document.createElement("script");
  script.setAttribute("src", "http://gsearch.scottreeddesign.com/js/jquery.gSearch-1.0-min.js");
  script.addEventListener('load', function() {
    var script = document.createElement("script");
    script.textContent = "(" + callback.toString() + ")();";
    document.body.appendChild(script);
  }, false);
  document.body.appendChild(script);
}


function LoadGoogle()
    {
        if(typeof google != 'undefined' && google && google.load)
        {
            google.load("search", "1");
        }
        else
        {
            // Retry later...
            setTimeout(LoadGoogle, 30);
        }
    }

LoadGoogle();

function main() {

    $("#div").css("border", ".5em solid black");

    $('head').append('<link rel="stylesheet" href="http://gsearch.scottreeddesign.com/css/gSearch.css" type="text/css" />');

    $('body').append('<div id="search-results"></div>');


$('#div').click(
    function() {

        $("#search-results").gSearch({search_text : 'example search'});

    });
}

// load scripts and execute the main function
addScripts(main);
4

1 に答える 1

0

質問のそのコードに関するいくつかの問題:

  1. callbackメインを2回発射しています。
  2. jQueryをロードしていませんが、JQ関数を使用しています。
  3. コールバックを使用して、ライブラリがロードされたときにアクションをチェーンします。以下のコードを参照してください。
  4. 「クローンを作成して変更」 しないでくださいaddScripts。そのような機能を「アトミック」に保ちます。
  5. Google APIキーを使用しません。これは検索APIに必要です(または少なくとも必要でした)。
  6. GoogleローダーとjQueryは、ユーザースクリプト環境では「うまく機能」しません。したがってaddJS_Node、Googleローダーの代わりにjQueryをロードするために使用します。
  7. 一般的には避けてください( Chromeユーザースクリプトに@include *も使用してください)。@matchスクリプトを実行するサイトのみをターゲットにします。
  8. IDを持つノードを使用しますが、divそのようなノードはコードによって作成されません(ほとんどのWebページには存在しない可能性があります)。

次のコードは、Chromeユーザースクリプト、Firefox Greasemonkeyスクリプト、およびその他のブラウザーで機能します。addJS_Nodeタイミングの問題とChromeでコードを挿入する必要があるために必要な、さまざまなコールバックとの広範な使用に注意してください。

// ==UserScript==
// @name    _Google Search API and plugin demo
// @match   http://stackoverflow.com/questions/*
// ==/UserScript==

function GM_main () {
    console.log ("Firing GM_main().");

    $("body").prepend ('<button id="gmSrchBtn">Run Google Search</button>')
    $('head').append (
        '<link rel="stylesheet" href="http://gsearch.scottreeddesign.com/css/gSearch.css" type="text/css" />'
    );
    $('body').prepend ('<div id="search-results"></div>');
    $('#gmSrchBtn').click ( function () {
        $("#search-results").gSearch ( {
            search_text: 'example search'
        } );
    } );
}

/*--- Load:
        1) Required/handy callbacks.
        2) Google base API
        3) Google search API
        4) jQuery
        5) The scottreeddesign jQuery plugin
*/

function GM_targetScopeFunctions () {
    window.gSearchApiIsLoaded   = false;

    window.gAPI_LoadedCB        = function () {
        console.log ("Google base API loaded.");
        google.load ("search", "1", {callback: gSearchAPI_LoadedCB} );
    }

    window.gSearchAPI_LoadedCB  = function () {
        console.log ("Google search API loaded.");
        window.gSearchApiIsLoaded   = true;
    }
}

addJS_Node (null, null, GM_targetScopeFunctions);
/*--- IMPORTANT!
    You will most likely need to get and use an API key for any but demo searching.
addJS_Node (null, "http://google.com/jsapi?callback=gAPI_LoadedCB&key=YOUR_API_KEY");
*/
addJS_Node (null, "http://google.com/jsapi?callback=gAPI_LoadedCB");
addJS_Node (
    null,
    "http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js",
    null,
    loadG_SrchPlugin
);
addJS_Node (GM_main);   //-- Loads main but does not run yet.

function loadG_SrchPlugin () {
    console.log ("jQuery loaded.");
    addJS_Node (
        null,
        "http://gsearch.scottreeddesign.com/js/jquery.gSearch-1.0-min.js",
        null,
        function () { addJS_Node (null, null, fireMainAfterSearchApiLoaded); }
    );

    function fireMainAfterSearchApiLoaded () {
        var srchLoadedIntrvl    = setInterval (checkForSrchAPI, 444);

        function checkForSrchAPI () {
            console.log ("In checkForSrchAPI().");
            if (gSearchApiIsLoaded) {
                clearInterval (srchLoadedIntrvl);
                GM_main ();
            }
        }
    }
}

function addJS_Node (text, s_URL, funcToRun, runOnLoad) {
    var D                                   = document;
    var scriptNode                          = D.createElement ('script');
    if (runOnLoad) {
        scriptNode.addEventListener ("load", runOnLoad, false);
    }
    scriptNode.type                         = "text/javascript";
    if (text)       scriptNode.textContent  = text;
    if (s_URL)      scriptNode.src          = s_URL;
    if (funcToRun)  scriptNode.textContent  = '(' + funcToRun.toString() + ')()';

    var targ = D.getElementsByTagName ('head')[0] || D.body || D.documentElement;
    targ.appendChild (scriptNode);
}
于 2012-10-04T11:10:43.253 に答える