2011-12-29 8 views
0

ChromeにGreasemonkeyスタイルのユーザースクリプトを使用して、指定したページにスクリプトを追加します。Chromeユーザースクリプトを使用して本文にスクリプトを追加します。

私はこのtrickを使用して、ユーザースクリプトにjQueryを追加します。

<h1>Test</h1>をjQueryのappend-methodを使用してページ本文に追加しようとすると、すべて正常に動作します。

しかし、JSスクリプトを追加しようとすると何も起こりません。

このような問題のトラブルシューティングを行うにはどうすればよいですか?

これは私の.user.jsファイルです:

// ==UserScript== 
// @match http://*/* 
// ==/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", "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"); 
    script.addEventListener('load', function() { 
    var script = document.createElement("script"); 
    script.textContent = "(" + callback.toString() + ")();"; 
    document.body.appendChild(script); 
    }, false); 
    document.body.appendChild(script); 
} 

// the guts of this userscript 
function main() { 

$(document).ready(function() { 
    $('body').append('<script type="text/javascript" src="http://timkl.com/wip/bibobRedesign/js/jquery.contenthack.js"></script>'); 
}); 

} 

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

答えて

2

jQueryの他のDOM要素とは異なるスクリプト要素を処理します。このanswerにはさらに詳しい情報があります。

スクリプトを追加する最も安全な方法は、jQueryライブラリを挿入するのと同じ方法を使用することです。

function main() { 
    var script = document.createElement("script"); 
    script.setAttribute("src", "http://timkl.com/wip/bibobRedesign/js/jquery.contenthack.js"); 
    document.body.appendChild(script); 
    $(document).ready(function() { 
     //$('body').append(); 
    }); 
} 

未テストオプション
あなたが(例えばLABjsなど)スクリプト・ローダを見てロードするためのスクリプトのたくさんをお持ちの場合は

あなたような何かを行うことができるかもしれません以下:

function addLABjs(callback) { 
    var script = document.createElement("script"); 
    script.setAttribute("src", "http://somepath.to/LAB.js"); 
    script.addEventListener('load', function() { 
     var script = document.createElement("script"); 
     script.textContent = "(" + callback.toString() + ")();"; 
     document.body.appendChild(script); 
    }, false); 
    document.body.appendChild(script); 
} 

// the guts of this userscript 


function main() { 
    $LAB.script("http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js").wait() 
     .script("http://timkl.com/wip/bibobRedesign/js/jquery.contenthack.js") 
     .script("YourOtherScript.js").wait(); 

    $(document).ready(function() { 
    }); 
} 

addLABjs(main); 
関連する問題