2011-07-07 51 views
0

我的最終目標是創建一個firefox擴展插件,將HTML按鈕插入到站點上,並讓它在我的擴展中激發定製代碼模塊中定義的函數。如何在firefox擴展中從注入的HTML按鈕觸發事件?

我試着實現Nickolay對這個question的回答。當我按一下按鈕我創造,雖然我得到以下錯誤在Firebug:

「未捕獲的異常:[異常...‘組件返回故障代碼:80070057(NS_ERROR_ILLEGAL_VALUE)nsIDOMEventTarget.dispatchEvent]’nsresult:」 80070057( NS_ERROR_ILLEGAL_VALUE)」的位置: 「JS框架::」

我的代碼:

onPageLoad: function(aEvent) { 
    Components.utils.import("chrome://my_ext/content/writeFile.jsm", my_ext); 
    //alert(foo()); - foo() is an function in the above code module I import 


    var doc = aEvent.originalTarget; // doc is document that triggered "onload" event 

    var event = doc.createEvent("Events"); 
    event.initEvent("my-custom-event", true, true); 

    var fblike = doc.getElementById("LikePluginPagelet"); 
    var button = doc.createElement("input"); 
    button.setAttribute("type", "button"); 
    button.setAttribute("value", "My Button"); 
    button.setAttribute('onclick', 'dispatchEvent(event)'); 

    fblike.appendChild(button, fblike); 

    var docx = event.originalTarget; 
    if(docx && docx.addEventListener) 
     docx.addEventListener("my-custom-event", function() {alert(foo()); }, false); 
}, 

我writeFile.jsm:

var EXPORTED_SYMBOLS = ["foo"]; 

function foo() { 
    return "foo test"; 
} 

任何關於如何解決這個問題的想法?我還應該提及,我對開發瀏覽器擴展完全陌生。

回答

0

終於得到它的工作。我不需要添加第二個偵聽器,只需要一行: button.addEventListener(「click」,foo,false);

我以前試過foo()而不是隻是foo,但失敗了,但現在工作得很好。

1

button.setAttribute('onclick', 'dispatchEvent(event)')不會做你認爲它會做的事情 - 當按鈕被點擊時,它需要click事件並嘗試分派它。然而,第二次分派事件是不允許的。你似乎想這是什麼:

button.addEventListener("click", function() { 
    button.dispatchEvent(event); 
}, false); 

這將創建一個功能關閉,將有機會獲得周圍的代碼的變量 - 包括buttonevent。進一步閱讀關閉:http://www.javascriptkit.com/javatutors/closures.shtml

+0

嗯,當我嘗試實現這個我得到了一個不明確的錯誤:「未捕獲的異常:[異常...」組件不可用「nsresult:」0x80040111(NS_ERROR_NOT_AVAILABLE)「位置:」JS框架:: chrome:/ /mezz/content/overlay.js :: :: line 43「data:no]」 第43行指代您建議的代碼(「button.onclick = function()...」)。谷歌搜索這個錯誤使我想到了不兼容Firefox的頁面,雖然不確定。 – Zaheer

+0

@ user773953:哦,您正在將該按鈕注入內容頁面。是的,'onclick'將不可用,您應該使用'addEventListener'來代替(無論如何這通常是一個好主意)。我編輯了我的答案以反映這一點。 –

+0

我想我錯過了一些東西。我現在沒有錯誤,但按鈕不起作用。當我點擊它時沒有任何反應。爲了澄清,我最初的代碼的最後三行仍然不錯?從「var docx = event.original ...」開始。 – Zaheer

相關問題