建構內容選單

按滑鼠左鍵動作時,系統會顯示內容選單 (通常稱為右鍵)。如要建立內容選單,請先將 "contextMenus" 權限新增至 manifest.json 檔案。

manifest.json:

  "permissions": [
    "contextMenus"
  ],

如果您想在選單項目旁邊顯示圖示,也可以選用 "icons" 鍵。在這個範例中,「全域 Google 搜尋」擴充功能的選單項目使用 16 x 16 的圖示。

顯示 16 x 16 圖示的內容選單項目。
帶有 16 x 16 圖示的內容選單項目。

本例的其餘部分擷取自「全域 Google 搜尋內容選單範例」,當中包含多個內容選單選項。如果擴充功能包含多個內容選單,Chrome 會自動將選單收合為單一父項選單,如下所示:

巢狀內容選單。
圖 4:內容選單和巢狀子選單。

這個範例可透過擴充功能 Service Worker 呼叫 contextMenus.create() 來顯示上述內容。子選單項目是從 locales.js 檔案匯入。然後 runtime.onInstalled 對其反覆進行疊代。

service-worker.js:

const tldLocales = {
  'com.au': 'Australia',
  'com.br': 'Brazil',
  ...
}

chrome.runtime.onInstalled.addListener(async () => {
  for (let [tld, locale] of Object.entries(tldLocales)) {
    chrome.contextMenus.create({
      id: tld,
      title: locale,
      type: 'normal',
      contexts: ['selection'],
    });
  }
});