firefox add-on

add-on是用來開發firefox的附加元件,其中開發方式有兩種,一種是採用browser線上開發,另一種則是在本機端開發,利用command line去對執行。在開發之前,需要先下載add-on sdk。(1.0版本只能運行在firefox4以上)

sdk下載完後執行:

source bin/activate (linux環境,若是window直接執行activate即可,接著就可以執行cfx。)

接著建立一個目錄,到目錄底下執行:

cfx init   (將會建立及配置基本的目錄檔案)

如果要執行可以使用:

cfx run

匯出檔案:

cfx xpi

以下是一個簡單範例:

main.js

const widgets = require("widget");
const pageMod = require('page-mod');
const data = require('self').data;
const tabs = require("tabs");
var workers = [];
var selector = pageMod.PageMod({
  include: ['*'],
  contentScriptWhen: 'ready',
  contentScriptFile: [data.url('page.js')],
  onAttach: function(worker) {
    worker.on("message",function(data){
        console.log(data);
    }); 
    workers.push(worker);
  }   
});   

var widget = widgets.Widget({
  id: "mozilla-link",
  label: "Mozilla website",
  contentURL: "http://www.mozilla.org/favicon.ico",
  onClick: function() {
    for(var i in workers){
        workers[i].postMessage("test");
    }   
  } 
}); 

console.log("The add-on is running."); 

data目錄的page.js

self.on("message",function(data){

    console.log(data);
    self.postMessage(document.title);
}); 

附加元件,會被顯示在browser的右下角,點選後即可觸發click事件,在終端機上即可看到console.log

add-on api