開始使用

擴充功能是由不同但連貫的元件組成。元件可包含背景指令碼內容指令碼選項頁面UI 元素和各種邏輯檔案。擴充功能元件是運用網頁開發技術建立:HTML、CSS 和 JavaScript。擴充功能的元件取決於其功能,因此可能不會要求所有選項。

本教學課程會建立一個擴充功能,讓使用者能變更 developer.chrome.com 中任何頁面的背景顏色。它會使用許多核心元件,提供與其關係的簡介示範。

首先,請建立新目錄來存放擴充功能的檔案。

你可以在這裡找到已完成的擴充功能。

建立資訊清單

擴充功能會從資訊清單開始,建立名為 manifest.json 的檔案,並加入以下程式碼。

{
  "name": "Getting Started Example",
  "version": "1.0",
  "description": "Build an Extension!",
  "manifest_version": 2
}

保留資訊清單檔案的目錄可在開發人員模式下,以擴充功能目前狀態新增為擴充功能。

  1. 前往 chrome://extensions 開啟「擴充功能管理」頁面。
    • 您也可以按一下 Chrome 選單,將遊標懸停在「More Tools」上,然後選取「Extensions」,即可開啟「擴充功能管理」頁面。
  2. 按一下「開發人員模式」旁的切換按鈕,即可啟用開發人員模式。
  3. 按一下「LOAD UNPACKED」按鈕,然後選取擴充功能目錄。

載入擴充功能

達陣!已成功安裝擴充功能。由於資訊清單中沒有任何圖示,因此系統會為該擴充功能建立一般工具列圖示。

新增操作說明

雖然已安裝擴充功能,但沒有任何操作說明。建立標題為 background.js 的檔案,並放入擴充功能目錄,藉此導入背景指令碼

背景指令碼和許多其他重要元件必須在資訊清單中註冊。 在資訊清單中註冊背景指令碼,即可告知擴充功能要參照哪個檔案,以及該檔案的行為方式。

{
  "name": "Getting Started Example",
  "version": "1.0",
  "description": "Build an Extension!",
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "manifest_version": 2
}

擴充功能現在知道其包含非持續性的背景指令碼,並會掃描註冊的檔案,找出需要監聽的重要事件。

安裝這項擴充功能後,需要永久變數中的資訊。請先在背景指令碼中加入 runtime.onInstalled 的監聽事件。在 onInstalled 事件監聽器中,擴充功能會使用 storage API 設定值。讓多個擴充功能元件可以存取該值並進行更新。

chrome.runtime.onInstalled.addListener(function() {
  chrome.storage.sync.set({color: '#3aa757'}, function() {
    console.log("The color is green.");
  });
});

大多數 API (包括 storage API) 都必須在資訊清單的 "permissions" 欄位下註冊,擴充功能才能使用這些 API。

{
  "name": "Getting Started Example",
  "version": "1.0",
  "description": "Build an Extension!",
  "permissions": ["storage"],
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "manifest_version": 2
}

返回擴充功能管理頁面,然後按一下「重新載入」連結。提供藍色連結「背景頁面」的新欄位「Inspect views」

檢查檢視畫面

點選這個連結即可查看背景指令碼的控制台記錄「The color is green.

介紹使用者介面

擴充功能可以採用多種使用者介面格式,但此方法會使用彈出式視窗。建立名稱為 popup.html 的檔案,並將其新增至目錄。此擴充功能會使用按鈕變更背景顏色。

<!DOCTYPE html>
<html>
  <head>
    <style>
      button {
        height: 30px;
        width: 30px;
        outline: none;
      }
    </style>
  </head>
  <body>
    <button id="changeColor"></button>
  </body>
</html>

和背景指令碼一樣,這個檔案必須在 page_action 下的資訊清單中指定為彈出式視窗。

{
  "name": "Getting Started Example",
  "version": "1.0",
  "description": "Build an Extension!",
  "permissions": ["storage"],
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "page_action": {
    "default_popup": "popup.html"
  },
  "manifest_version": 2
}

工具列圖示的標示也會納入 default_icons 欄位的 page_action 下方。在這裡下載圖片資料夾、解壓縮,然後放在擴充功能的目錄中。請更新資訊清單,讓擴充功能瞭解如何使用映像檔。

{
  "name": "Getting Started Example",
  "version": "1.0",
  "description": "Build an Extension!",
  "permissions": ["storage"],
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "page_action": {
    "default_popup": "popup.html",
    "default_icon": {
      "16": "images/get_started16.png",
      "32": "images/get_started32.png",
      "48": "images/get_started48.png",
      "128": "images/get_started128.png"
    }
  },
  "manifest_version": 2
}

擴充功能也會在擴充功能管理頁面顯示圖片、權限警告和網站小圖示。這些映像檔會列於 icons 的資訊清單中。

{
  "name": "Getting Started Example",
  "version": "1.0",
  "description": "Build an Extension!",
  "permissions": ["storage"],
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "page_action": {
    "default_popup": "popup.html",
    "default_icon": {
      "16": "images/get_started16.png",
      "32": "images/get_started32.png",
      "48": "images/get_started48.png",
      "128": "images/get_started128.png"
    }
  },
  "icons": {
    "16": "images/get_started16.png",
    "32": "images/get_started32.png",
    "48": "images/get_started48.png",
    "128": "images/get_started128.png"
  },
  "manifest_version": 2
}

如果在這個階段重新載入擴充功能,擴充功能會顯示灰階圖示,但不會有任何功能差異。由於 page_action 已在資訊清單中宣告,因此是由擴充功能判斷使用者何時能與 popup.html 互動。

使用 runtime.onInstalled 事件監聽器事件中的 declarativeContent API,在背景指令碼中新增宣告的規則。

chrome.runtime.onInstalled.addListener(function() {
  chrome.storage.sync.set({color: '#3aa757'}, function() {
    console.log('The color is green.');
  });
  chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
    chrome.declarativeContent.onPageChanged.addRules([{
      conditions: [new chrome.declarativeContent.PageStateMatcher({
        pageUrl: {hostEquals: 'developer.chrome.com'},
      })
      ],
          actions: [new chrome.declarativeContent.ShowPageAction()]
    }]);
  });
});

擴充功能需要權限才能存取資訊清單中的 declarativeContent API。

{
  "name": "Getting Started Example",
...
  "permissions": ["declarativeContent", "storage"],
...
}

彈出式廣告

當使用者前往包含 "developer.chrome.com" 的網址時,瀏覽器工具列會顯示全彩的頁面動作圖示。做為全彩圖示時,使用者只要按一下圖示即可查看 pop.html。

彈出式 UI 的最後一個步驟是為按鈕新增顏色。請建立含有下列程式碼的 popup.js 檔案,並將其新增至擴充功能目錄。

let changeColor = document.getElementById('changeColor');

chrome.storage.sync.get('color', function(data) {
  changeColor.style.backgroundColor = data.color;
  changeColor.setAttribute('value', data.color);
});

這個程式碼可從 popup.html 擷取按鈕,並要求儲存空間中的顏色值。然後套用顏色做為按鈕的背景。在 popup.html 中加入 popup.js 的指令碼標記。

<!DOCTYPE html>
<html>
...
  <body>
    <button id="changeColor"></button>
    <script src="popup.js"></script>
  </body>
</html>

重新載入擴充功能即可查看綠色按鈕。

圖層邏輯

擴充功能現在會知道使用者應可在 developer.chrome.com 中找到彈出式視窗,並顯示彩色按鈕,但需要邏輯才能進行進一步的使用者互動。更新 popup.js 以加入下列程式碼。

let changeColor = document.getElementById('changeColor');
...
changeColor.onclick = function(element) {
  let color = element.target.value;
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    chrome.tabs.executeScript(
        tabs[0].id,
        {code: 'document.body.style.backgroundColor = "' + color + '";'});
  });
};

更新後的程式碼會在按鈕上新增 onclick 事件,進而觸發以程式輔助方式插入的內容指令碼。這會將網頁的背景顏色變成按鈕的顏色。使用程式輔助插入功能即可讓使用者叫用的內容指令碼,而不是將不必要的程式碼自動插入網頁中。

資訊清單需要 activeTab 權限,才能允許擴充功能暫時存取 tabs API。這可讓擴充功能呼叫 tabs.executeScript

{
  "name": "Getting Started Example",
...
  "permissions": ["activeTab", "declarativeContent", "storage"],
...
}

擴充功能現在可正常運作!重新載入擴充功能,重新整理這個頁面、開啟彈出式視窗,然後按一下按鈕,讓按鈕變成綠色!不過,部分使用者可能會想將背景變更為其他顏色。

為使用者提供選項

這個擴充功能目前只能讓使用者將背景變更為綠色。提供選項頁面,可讓使用者進一步掌控擴充功能的功能,並進一步自訂瀏覽體驗。

首先,請在名為 options.html 的目錄中建立檔案,並加入以下程式碼。

<!DOCTYPE html>
<html>
  <head>
    <style>
      button {
        height: 30px;
        width: 30px;
        outline: none;
        margin: 10px;
      }
    </style>
  </head>
  <body>
    <div id="buttonDiv">
    </div>
    <div>
      <p>Choose a different background color!</p>
    </div>
  </body>
  <script src="options.js"></script>
</html>

然後在資訊清單中註冊選項頁面

{
  "name": "Getting Started Example",
  ...
  "options_page": "options.html",
  ...
  "manifest_version": 2
}

重新載入擴充功能,然後按一下「詳細資訊」

檢查檢視畫面

向下捲動詳細資料頁面,然後選取「Extension options」(擴充功能選項) 即可查看選項頁面,但該頁面目前會顯示為空白。

擴充功能選項

最後一步是新增選項邏輯。使用下列程式碼,在擴充功能目錄中建立名為 options.js 的檔案。

let page = document.getElementById('buttonDiv');
const kButtonColors = ['#3aa757', '#e8453c', '#f9bb2d', '#4688f1'];
function constructOptions(kButtonColors) {
  for (let item of kButtonColors) {
    let button = document.createElement('button');
    button.style.backgroundColor = item;
    button.addEventListener('click', function() {
      chrome.storage.sync.set({color: item}, function() {
        console.log('color is ' + item);
      })
    });
    page.appendChild(button);
  }
}
constructOptions(kButtonColors);

接著,系統會提供四種顏色選項,在選項頁面上以按鈕的形式產生,並含有點擊事件事件監聽器。當使用者點選某個按鈕時,系統會更新擴充功能的全域儲存空間中的顏色值。由於所有擴充功能檔案都會從全域儲存空間提取顏色資訊,因此不必更新其他值。

後續行動

恭喜!現在,目錄內含功能齊全的 Chrome 擴充功能,而且功能完善。

後續步驟

  • Chrome 擴充功能總覽會針對擴充功能架構進行概略說明,並詳細介紹開發人員需要熟悉的具體概念。
  • 如要瞭解對擴充功能進行偵錯的選項,請參閱偵錯教學課程
  • Chrome 擴充功能可存取強大的 API,而且不侷限於開放網路可用的 API。chrome.* API 說明文件會逐一介紹各項 API。
  • 開發人員指南提供數十種其他說明文件連結,協助您瞭解建立進階擴充功能的相關文件。