建構內容選單

滑鼠的替代點擊 (通常稱為按右鍵) 會顯示內容選單。如要建構內容選單,請先將 "contextMenus" permission 新增至 manifest.json 檔案。

manifest.json:

  "permissions": [
    "contextMenus"
  ],

如要在選單項目旁邊顯示圖示,請視需要使用 "icons" 鍵。在本例中,「Global Google Search」擴充功能的選單項目使用 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'],
    });
  }
});