簡體   English   中英

幫我創建一個Firefox擴展(Javascript XPCOM組件)

[英]Help me create a Firefox extension (Javascript XPCOM Component)

我一直在尋找不同的教程,我知道我很接近,但我在實現細節上迷失了,因為其中一些有點過時了,自Firefox 3以來有些事情發生了變化。我已經編寫了javascript for firefox擴展 ,現在我需要將它變成一個XPCOM組件。

這是我需要的功能:我的Javascript文件很簡單,我有兩個函數startServer()stopServer 我需要在瀏覽器啟動時運行startServer() ,在firefox退出時運行stopServer()

編輯:

我用一個有效的解決方案更新了我的代碼(感謝Neil)。 以下是MyExtension/components/myextension.js

Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
const CI = Components.interfaces, CC = Components.classes, CR = Components.results;

// class declaration
function MyExtension() {}

MyExtension.prototype = {
    classDescription: "My Firefox Extension",
    classID:          Components.ID("{xxxx-xxxx-xxx-xxxxx}"),
    contractID:       "@example.com/MyExtension;1",
    QueryInterface: XPCOMUtils.generateQI([CI.nsIObserver]),

    // add to category manager
    _xpcom_categories: [{
        category: "profile-after-change"
    }],

    // start socket server
    startServer: function () { /* socket initialization code */ },

    // stop socket server
    stopServer: function () { /* stop server */ },


    observe: function(aSubject, aTopic, aData) 
    {
        var obs = CC["@mozilla.org/observer-service;1"].getService(CI.nsIObserverService);

        switch (aTopic) 
        {
            case "quit-application":
                this.stopServer();
                obs.removeObserver(this, "quit-application");
                break;
            case "profile-after-change":
                this.startServer();
                obs.addObserver(this, "quit-application", false);
                break;
            default:
                throw Components.Exception("Unknown topic: " + aTopic);
        }
    }
};

var components = [MyExtension];

function NSGetModule(compMgr, fileSpec) {
    return XPCOMUtils.generateModule(components);
}

據我所知,您的所有代碼都會進入您的組件。

您需要一個代表組件的JavaScript對象,並將其注冊到組件注冊器。 (它可以是一個新對象,也可以多任務一個現有對象。)這樣做的方式取決於你是針對Firefox 3.x還是Firefox 4。

您需要使用類別管理器注冊profile-after-changeprofile-after-change通知。 這樣做的方式還取決於你是針對Firefox 3,Firefox 3.5 / 6還是Firefox 4。

觸發更改后的通知觸發后,將創建組件並調用observe方法。 這是您啟動服務器的位置,還要求觀察退出應用程序通知。 請注意,這也會調用observe方法,因此必須檢查它獲取的通知。

function myExt() {}
myExt.prototype = {
  observe: function(aSubject, aTopic, aData) {
    switch (aTopic) {
      case "quit-application":
        stopServer();
        obs.removeObserver(this, "quit-application");
        break;
      case "profile-after-change":
        startServer();
        obs.addObserver(this, "quit-application", false);
        break;
    }
  }
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM