2013-08-02 100 views
2

我正在創建Firefox擴展。我想加載我的外部js文件加載時間使用Firefox擴展所有網頁。我可以在我的HTML文件中成功加載加載事件中的所有js文件。但我怎樣才能執行到我的擴展。在頁面加載後加載腳本 - Firefox擴展

window.onload = load; 
function load() 
{    
     var filerefs=document.createElement('script') 
     filerefs.setAttribute("type","text/javascript") 
     filerefs.setAttribute("src", 'http://code.jquery.com/jquery-1.9.1.min.js') 
     var head = doc.getElementsByTagName("head")[ 0 ].appendChild(filerefs); 
} 

請指導我。

+0

是'負載()'不解僱或者被它發射,但你得到一個錯誤/標籤沒有加載? – putvande

+0

你的意思是你想要在每個打開的網頁上注入一些JS? –

+0

應該注意的是,出於安全性和兼容性的原因,強烈建議將(遠程)javascript注入隨機頁面。如果您是SDK用戶,請改爲使用page-mod。 – nmaier

回答

2

如果你想檢測頁面加載,而不是應用負載,你應該做這樣的(第一部分應該是你的主要覆蓋文件):

// do not try to add a callback until the browser window has 
// been initialised. We add a callback to the tabbed browser 
// when the browser's window gets loaded. 
window.addEventListener("load", function (event) { 
    // Add a callback to be run every time a document loads. 
    // note that this includes frames/iframes within the document 

    gBrowser.addEventListener("load", load(event), true); 
}, false); 

借鑑here

我將事件添加到加載函數中,因爲事件不僅會觸發負載本身,還會觸發其他元素,因此您必須驗證您只做了一次(參考here):

function load(event) { 
    if (event.originalTarget.nodeName == "#document") { 
     var htmlns = "http://www.w3.org/1999/xhtml"; 
     var doc = gBrowser.selectedBrowser.contentDocument; 

     var filerefs = doc.createElementNS(htmlns,'script'); 
     filerefs.setAttribute("type","text/javascript"); 
     filerefs.setAttribute("src", "http://code.jquery.com/jquery-1.9.1.min.js"); 
     doc.getElementsByTagName("head")[0].appendChild(filerefs); 
    } 
} 

而不是使用document.getElement ...,我們必須定位在頁面的內容上,否則你會從你的插件中獲取元素(使用gBrowser.selectedBrowser.contentDocument可以訪問當前頁面的dom)。在創建元素上,我們希望創建html元素,因此您可以定義和使用html命名空間(參考文獻here)。

這應該做的伎倆:

enter image description here

+0

我想找到所有img標籤爲加載頁面。請幫助我 –

+0

你只想在頁面中找到圖像?您沒有其他的理由來加載頁面加載腳本?如果是這樣,你可能想接受這個問題,並開始一個新的請求,因爲這在你的原始問題中沒有提到,這個可能對任何具有有效用例的人都有用。 至於找到圖像,請更好地解釋你想要對新問題的圖像做什麼 –

+0

我接受這個答案。我的另一個問題鏈接http://stackoverflow.com/questions/18031833/call-jquery-function-after-page-load-not-working-firefox-extension請幫我 –