2011-12-29 95 views
0

我想在Chrome中使用Greasemonkey樣式的用戶腳本將腳本添加到給定頁面。使用Chrome用戶腳本向正文添加腳本

我使用這個trick來添加jQuery到我的用戶腳本。

如果我嘗試使用jQuery的append-method將<h1>Test</h1>添加到頁面主體,則一切正常。

但是,如果我嘗試追加一個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);