2009-09-30 146 views
0

我創建一個JavaScript XPCOM組件它的源代碼如下 -未定義JavaScript警報。 。

Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); 

function callback() { } 

callback.prototype = { 
    classDescription: "My Hello World Javascript XPCOM Component", 
    classID:   Components.ID("{3459D788-D284-4ef0-8AFF-96CBAF51BD35}"), 
    contractID:  "@jscallback.p2psearch.com/f2f;1", 
    QueryInterface: XPCOMUtils.generateQI([Components.interfaces.ICallback]), 
    received:function(data){ 
      alert("Received: " +data); 
     }, 
    status:function(data){ 
      alert("Status: "+data); 
      }, 
    expr:function(data){ 
      alert("Expr: "+expr); 
     } 
}; 
var components = [callback]; 
function NSGetModule(compMgr, fileSpec) { 
    return XPCOMUtils.generateModule(components); 
} 

當我把它用:

try { 
    const p2pjcid = "@jscallback.p2psearch.com/f2f;1"; 
    var jobj = Components.classes[p2pjcid].createInstance(); 
    jobj = jobj.QueryInterface(Components.interfaces.ICallback); 
    jobj.received("Hello from javascript") 
    } 
    catch (err) { 
    alert(err); 
    return; 
    } 

我得到錯誤爲:

[Exception... "'[JavaScript Error: "alert is not defined" {file: "file:///C:/Documents%20and%20Settings/mypc/Application%20Data/Mozilla/Firefox/Profiles/ngi5btaf.default/extensions/[email protected]/components/callback.js" line: 11}]' when calling method: [ICallback::received]" nsresult: "0x80570021 (NS_ERROR_XPC_JAVASCRIPT_ERROR_WITH_DETAILS)" location: "JS frame :: chrome://sample/content/clock.js :: initClock :: line 28" data: yes] 

回答

3

這是因爲alert不是在XPCOM代碼中定義的(儘管您可以獲取組件)。在擴展程序中提醒並不是一個好主意,因爲它會阻止用戶與他們所在的頁面進行交互。使用非模態烤麪包器框通知功能:

const alert = Components.classes['@mozilla.org/alerts-service;1'] 
        .getService(Components.interfaces.nsIAlertsService) 
        .showAlertNotification; 

使用它的語法如下:alert(icon, title, body)

這是more info on MDC

+0

如果我需要訪問javascript dom ??由於我也正在獲取文檔未定義。你能指點我一個鏈接嗎?謝謝 – Xinus 2009-09-30 10:28:51

+0

搜索XPCSafeJSObjectWrapper等。 – 2009-09-30 19:07:49

+0

XPCNativeWrapper也應該是你要找的。 – 2009-09-30 19:21:28

1

您還可以使用JavaScript組件中的dump()。