2016年9月16日

摩茲動手做(五)自己的瀏覽器自己改─使用新版 Firefox Addon SDK 開發簡單的附加元件

本文原文出自《小克'S 部落格》,作者小克更新謀智台客〈自己的瀏覽器自己改 (Part I) -利用Firefox Addon SDK開發簡單的附加元件〉一文,以新的 jpm 工具相關資訊,取代原文中使用的舊版 cfx 工具而成。

也歡迎參閱由 WM 撰寫的〈摩茲動手做(二)用 Add-on SDK 寫簡單的 Firefox 套件〉 一文。如果有開發相關疑問,歡迎加入 MozTW dev/add-on 開發 Telegram 聊天頻道,一起討論套件開發的心得與問題。

前言

Firefox 最受歡迎的特色之一,就是量多而且質精的附加元件 (Add-on)。在 Firefox 附加元件網站中,您可以找到各式各樣的附加元件,滿足您上網的各種需求。在這篇文章中,我們將會介紹如何利用 Firefox Add-on SDK 撰寫簡單的附加元件,改變網頁的外觀與行為。

即使不是自己架設的網站,我們也能隨心所欲的改善它們的使用經驗!

準備工作

為了減輕開發者的負擔,Mozilla 推出 Add-on SDK,取代原來基於 XUL 技術的附加元件框架。相較於傳統的 XUL,Add-on SDK 提供更多簡單易用的 API,簡化開發流程,另外也提供了許多新的使用者介面元素,來配合新版的 Firefox 介面。

為了能夠使用最新的 API,建議您先更新 Firefox 到最新版

您還需要安裝最新版的 Add-on SDK,以下將以 Linux 平台作為教學範例 ( OS X 也適用 ),若是使用 Windows 請參考 Install the Add-on SDK

首先下載最新版的 Add-on SDK,您需要先安裝 npm (包含在 Node.js 中)。可以使用以下指令確認是否安裝過:

/usr/bin/env node -v

若顯示錯誤訊息如 /usr/bin/env: node: No such file or directory,則透過指令安裝:

Ubuntu

sudo apt-get install nodejs-legacy

OS X(請先安裝 Homebrew 套件管理工具

brew install node

接者透過 npm 安裝 jpm

npm install jpm --global

安裝後測試看看是否成功:

jpm

若安裝成功您應該會看到 jpm 的可用指令統整畫面。

特別的是,只要安裝 jpm 時有使用 --global flag,就不用像舊式的 cfx 工具,需要使用指令啟用 Add-on SDK 環境。

初始化一個新的專案

Web 工程師都知道要學習 HTML、JavaScrprt、CSS 最好的資源就是 Mozilla Developer Network。我們就試著用 Firefox Add-on 來把 MDN 調教改造成我們想要的樣子。

我們會先示範如何插入 JavaScript 來改變 MDN 的背景顏色,接著我們再示範如何在 MDN 的首頁上插入自己的按鈕,並且可以讓按鈕執行我們自己定義的 JavaScript。

套用 Add-on 之前的 MDN 網站

假設我們把這個新的專案叫作 mdn-mod ,第一步我們先讓 Add-on SDK 幫我們生成必要的檔案與目錄結構:

mkdir mdn-mod
cd mdn-mod
jpm init

當執行完 jpm init 之後,jpm 會詢問我們關於此附加元件的一些資訊,例如程式名稱、版本號、作者、授權條款等等,這些資訊會被用來建立 package.json 檔。現在我們只要連按 Enter 使用預設值。

完成後,我們的 mdn-mod 資料夾就會出現以下的檔案:

.
├── index.js     // Add-on 主要的 JavaScript 程式碼,程式的進入點
├── README.md    // 說明文件
├── package.json // 定義這個 Add-on 的 metadata
└── test         // 測試檔案,之後再介紹
    └── test-main.js

用 page-mod 插入 JavaScript 到指定網站

Add-on SDK 提供的一個實用 API 叫作 page-mod,其用途是當 Firefox 開啟指定的網站時,就插入一段自己的 JavaScript 到頁面上,因此可以改變特定網站的行為。

首先我們打開 index.js,加入以下幾行程式碼:

var pageMod = require("sdk/page-mod");
var data = require("sdk/self").data;

pageMod.PageMod({
    include: "*.mozilla.org",
    contentScriptFile: data.url("my-script.js")
});

第五行的 include: “*.mozilla.org” 就是我們希望套用的網址(* 代表萬用字元)。只要 Firefox 開啟的網址是以 mozilla.org 結尾,就會插入 contentScriptFile 指定的 JavaScript 檔案。在這裡我們使用了 data.url(“my-script.js”),意思是放在 data/ 資料夾下的 my-script.js 檔案。

改變 MDN 背景顏色

目前為止我們還沒定義 Content Script 要執行什麼。現在馬上新增一個檔案 data/my-script.js,插入以下一行簡單的程式碼:

document.body.style.background="red";

這行代碼會把 <body> 的背景設成紅色,等同於以下這段 CSS 的效果:

body {
    background-color: red;
}

使用乾淨的瀏覽器進行測試

完成上述步驟以後,我們的 Add-on 已經可以準備測試了。但是我們日常使用的 Firefox 可能有很多個人設定,或是安裝了很多其他 Add-on,會干擾我們的測試。此時我們只要執行

jpm run

Add-on SDK 就會幫我們開啟一個完全乾淨的 Firefox 使用者設定檔(Profile),讓我們可以在近乎出廠設定的 Firefox 底下測試我們的 Add-on。


乾淨的 Firefox Profile

當我們在新開的 Firefox 裡面開啟 http://developer.mozilla.org/,毫不意外的 MDN 的背景就變成紅色了!


MDN 的背景已經被改成紅色

添加新按鈕

除了改變現有的頁面以外,我們也可以自由的插入任何自己想要的元件。讓我們再次打開 data/my-script.js,加入以下程式碼:

var button = "<button onClick='alert(\"Hi!\")'>CLICK ME</button>";
document.body.innerHTML = button + document.body.innerHTML;

再這段程式碼裡面,我們定義了一個 html5 的按鈕,並且讓它被按下 (觸發 onClick 事件) 時,跳出一個訊息框說「Hi!」 (alert('Hi!')),緊接著就把這個按鈕插入到 body tag 的最前面。

當我們再次執行 cfx run 來瀏覽 MDN 時,就會看到畫面最上方出現了一個按鈕。

出現了 CLICK ME 按鈕

按下按鈕馬上跳出寫著「Hi!」的訊息框。

跳出了寫著「Hi!」的訊息框

打包出貨

如此一來我們的 Add-on 就大功告成了!如果要把這個 Add-on 包裝成可以分享的 xpi 格式,只要執行 jpm xpi 即可。

Add-on SDK 會生成一個副檔名為 .xpi 的安裝檔。不論是要直接傳給親朋好友,或是拿去 Firefox 附加元件網站上架都可以!

以上就是一個簡單的 Add-on 教學。

參考資訊

  1. Firefox 附加元件網站 https://add-ons.mozilla.org
  2. Firefox Add-on SDK (MDN) https://developer.mozilla.org/en-US/Add-ons/SDK
  3. Overlay Extension using XUL https://developer.mozilla.org/en-US/Add-ons/Overlay_Extensions
  4. Install the Add-on SDK https://developer.mozilla.org/en-US/Add-ons/SDK/Tools/jpm#Installation
  5. package.json 格式說明 https://developer.mozilla.org/en-US/Add-ons/SDK/Tools/package_json
  6. page-mod https://developer.mozilla.org/en-US/Add-ons/SDK/High-Level_APIs/page-mod
  7. Packaging the add-on https://developer.mozilla.org/en-US/Add-ons/SDK/Tutorials/GettingStarted(jpm)#Packagingtheadd-on

授權

本篇原始著作衍生自〈謀智台客〉自己的瀏覽器自己改 (Part I) -利用Firefox Addon SDK開發簡單的附加元件一文,作者為 Lyu Shing,以創用 CC 姓名標示—相同方式分享條款 3.0 或更新版本授權釋出。

原文 / 自己的瀏覽器自己改 (Part 2) -利用新的 jpm Firefox Addon SDK 開發簡單的附加元件 - 小克’s 部落格
授權 / 創用CC 姓名標示-相同方式分享 4.0 國際版
作者 / 小克

φ 小克 撰寫 - Toppy、Irvin 編輯

34 則留言:

  1. It is undisputed that Sociology Assignment Writing Services pose challenges for students because preparation takes into consideration a lot of details needed for Sociology Coursework Writing Services and in-depth knowledge on the topic in order to come up with award winning Custom Sociology Research Paper Writing Services.

    回覆刪除
  2. There are academic nursing writing help companies whose ultimate goal is to provide Help with Nursing Writing Services since they are aware most nursing essay writing service part-time students lack enough time to complete their college custom nursing assignments.

    回覆刪除
  3. Telecom Project manager in the telecom space are the people in charge of a specific project or projects within a telecom business. As a project manager, their responsibilities are to plan, budget, manage and document all stages of a certain project. Telecom Project Managers are accountable for coordinating telecommunication systems installation projects for multiple businesses across the various platforms.

    回覆刪除
  4. In which different sorts of creating are accessible: piece shaping, Dissertation Writing Help, Research Paper Assistance, Analysis, Literature Review, articles, and so forth.
    Do My Homework Online
    Write My Assignment
    reflective essay writing service

    回覆刪除
  5. Custom Social Science Writing Services is very popular for students in search for social science essay services and social science research paper services.

    回覆刪除
  6. There are many engineering assignment help writing services and Engineering Writing Services to choose from for those stuck with their engineering research paper writing services and engineering term paper writing services.

    回覆刪除
  7. Best Offers on Toys Get the best deals on all types of toys available on Amazon and Walmart. Know more about our products from lenoxtons20

    回覆刪除
  8. The ultimate goal of online psychology research paper writing services is to provide Psychology Assignment Writing Services and psychology research paper services since most psychology coursework writing service students lack time to complete their custom psychology coursework writing services.

    回覆刪除
  9. pay someone for online class help the understudies can at whatever point look for help from online associations. They begin making them an undertaking that is absolutely fascinating and legitimate.reflective essay
    Pay for essay assignment help

    回覆刪除
  10. The ultimate goal of online psychology research paper writing services is to provide Psychology Assignment Writing Services and psychology research paper services since most psychology coursework writing service students lack time to complete their custom psychology coursework writing services.

    回覆刪除
  11. An Audio Visual Technician sets up, tests, operates, assesses, and repairs equipment required for live events, such as music concerts, sporting events, virtual classrooms, video conferences, such as Skype or Webex, and entertainment shows. These individuals work with projectors, sound systems, microphones, sound mixing equipment, overhead projectors, video cameras, recording equipment, adjust amplifiers, video screens, speakers, and lighting. An Audio Visual Technician aid educators, program producers, recording production engineers, and presenters to generate sound, images, and videos to produce CDs, DVDs, as well as TV and film productions.

    回覆刪除
  12. Healthcare research paper writing services are essential and it has become very popular for those seeking healthcare essay writing services since most of them seek Healthcare Assignment Writing Services.

    回覆刪除
  13. https://mozlinks.moztw.org/2016/09/firefox-addon-sdk-jpm.html?showComment=1589475191368#c1544607407219825787
    read more

    回覆刪除
  14. Welcome to Trendstechblog. Our Aim at the supply our readers with more information about the newest technology news, upcoming gadgets, mobile apps social media, daily changing business strategies, day to day changes in digital marketing.

    tech write for us

    回覆刪除
  15. If you are searching for genuine notary public translation service in Singapore than you are landed on the right place at Language translation services Singapore Our experts deliver well precise,meticulous translation with 100% accuracy.

    回覆刪除
  16. Our assignment help expert have a clear understanding of requirements as per the college scenario, thus they know well what works for which college or university. This recognition makes them more competent in solving students' queries when they come up with the search in mind who can "get assignment done".

    回覆刪除
  17. This really Excellent and, Amazing. I’ll bookmark your website and take the feeds also. I’m happy to find so many helpful information here in the release. thanks for sharing and its really great dear friend. hnd assignment help -
    economics assignment help -
    programming assignment help

    回覆刪除
  18. I am very happy and so fresh feel after read this article. This is the kind of manual that needs to be given and not the random misinformation that’s at the other articles. Please admin share more and I am coming back to your blog for more soon. Bye assignment help in australia -
    Assignment Help Melbourne -
    Assignment Help Perth

    回覆刪除
  19. Usually, I never comment on blogs but your article is so convincing that I never stop myself to say something about it. You’re doing a great job Man, Keep it up. We provide the highest quality in mold remediation services, asbestos removal & water dry out in Maricopa County including Phoenix, Mesa, Chandler, Glendale, Scottsdale and Gilbert! for more information visit our website Mold Removal Services Arizona

    回覆刪除
  20. Such great information for the blogger I am a professional blogger thanks. The La Barbera proudly serves a great combination of modern and traditional barbery. for more information visit our website hair salon granbury texas

    回覆刪除
  21. Hi, I am John Smith, I am working as a technical manager at email support. I have 3 years of experience in this field. If you have any problems related to Centurylink email login problems, then please contact for instant help related to email problems.

    回覆刪除
  22. I’m Sakht. I’m a writer living in London, UK. I am a fan of technology. You can visit my store.
    mcafee.com/activate
    Norton.com/setup
    mcafee.com/activate
    Norton.com/setup

    回覆刪除
  23. I am working as a SEO Analyst.My blog gives information about latest
    technologies and IT Courses.
    IT Education

    回覆刪除
  24. The ultimate goal of criminology assignment writing services is to provide Criminology Essay Writing Services and criminology coursework writing services since criminology assignments help service seekers lack time to complete their criminology research writing services.

    回覆刪除
  25. You are not the only one who is facing this issue. In fact, almost every user faces the Epson printer offline every other day. Luckily, the problem is not with the printer. There are many ways to resolve this issue without the help of technical support executives.

    回覆刪除