chrome.commands

說明

你可以使用指令 API 新增鍵盤快速鍵,藉此在擴充功能中觸發某些動作,例如開啟瀏覽器動作的動作,或是傳送指令給擴充功能。

資訊清單

您必須在資訊清單中宣告下列金鑰,才能使用這個 API。

"commands"

概念和用法

Commands API 可讓擴充功能開發人員定義特定指令,並繫結至預設的按鍵組合。請務必在擴充功能資訊清單中,將擴充功能接受的每個指令宣告為 "commands" 物件的屬性。

屬性鍵會做為指令的名稱。指令物件可採用兩種屬性。

suggested_key

選用的屬性,用於宣告指令的預設鍵盤快速鍵。如果省略,該指令將解除繫結。此屬性可以採用字串或物件值。

  • 字串值指定在所有平台上使用的預設鍵盤快速鍵。

  • 物件值可讓擴充功能開發人員自訂每個平台的鍵盤快速鍵。提供平台專屬捷徑時,有效的物件屬性為 defaultchromeoslinuxmacwindows

詳情請參閱「按鍵組合相關規定」一節。

description

這個字串用於提供使用者有關指令用途的簡短說明。這個字串會顯示在擴充功能鍵盤快速鍵管理 UI 中。標準指令必須提供說明,但動作指令會忽略說明。

一個擴充功能可以有許多指令,但最多只能指定四個建議的鍵盤快速鍵。使用者可以在 chrome://extensions/shortcuts 對話方塊中手動新增更多捷徑。

支援的金鑰

以下是可用的指令快速鍵。主要定義須區分大小寫。如果嘗試載入的擴充功能使用了錯誤的金鑰,將在安裝期間發生資訊清單剖析錯誤。

Alpha 測試版金鑰
A ... Z
數字鍵
0 ... 9
標準金鑰字串

一般:CommaPeriodHomeEndPageUpPageDownSpaceInsertDelete

方向鍵:UpDownLeftRight

媒體鍵:MediaNextTrackMediaPlayPauseMediaPrevTrackMediaStop

輔助鍵字串

CtrlAlt (在 macOS 上的 Option)、ShiftMacCtrl (僅限 macOS)、Command (僅限 macOS)、Search (僅限 ChromeOS)

按鍵組合需求

  • 擴充功能指令快速鍵必須包含 CtrlAlt

    • 修飾符不得與媒體鍵搭配使用。
  • macOS Ctrl 會自動轉換為 Command

    • 如要在 macOS 上使用 Control 鍵,請在定義 "mac" 快速鍵時,將 Ctrl 替換為 MacCtrl

    • MacCtrl 與其他平台合併使用會造成驗證錯誤,並阻止使用者安裝擴充功能。

  • Shift 是所有平台的選用修飾符。

  • Search 是 ChromeOS 專屬的選用輔助鍵。

  • 某些作業系統和 Chrome 快速鍵 (例如視窗管理) 一律會優先於擴充功能指令捷徑,且無法覆寫。

處理指令事件

manifest.json:

{
  "name": "My extension",
  ...
  "commands": {
    "run-foo": {
      "suggested_key": {
        "default": "Ctrl+Shift+Y",
        "mac": "Command+Shift+Y"
      },
      "description": "Run \"foo\" on the current page."
    },
    "_execute_action": {
      "suggested_key": {
        "windows": "Ctrl+Shift+Y",
        "mac": "Command+Shift+Y",
        "chromeos": "Ctrl+Shift+U",
        "linux": "Ctrl+Shift+J"
      }
    }
  },
  ...
}

在服務工作站中,您可以使用 onCommand.addListener 將處理常式繫結到資訊清單中定義的每個指令。例如:

service-worker.js:

chrome.commands.onCommand.addListener((command) => {
  console.log(`Command: ${command}`);
});

動作指令

_execute_action (Manifest V3)、_execute_browser_action (Manifest V2) 和 _execute_page_action (Manifest V2) 指令會分別保留用於觸發動作、瀏覽器動作或網頁動作的動作。這些指令不會分派 command.onCommand 事件 (例如標準指令)。

如果您需要根據彈出式視窗展開動作,請考慮在彈出式視窗的 JavaScript 中監聽 DOMContentLoaded 事件。

範圍

根據預設,指令範圍僅限 Chrome 瀏覽器。也就是說,當瀏覽器沒有聚焦時,指令快速鍵就會停用。從 Chrome 35 版開始,擴充功能開發人員可以選擇將指令標示為「全域」。在 Chrome「沒有」焦點的情況下,全域指令也能正常運作。

通用指令的鍵盤快速鍵建議上限為 Ctrl+Shift+[0..9] 個。這是一種保護措施,可將覆寫其他應用程式中捷徑的風險降到最低;舉例來說,如果將 Alt+P 當做全域允許,則用於開啟列印對話方塊的鍵盤快速鍵可能無法在其他應用程式中運作。

使用者可以使用 chrome://extensions/shortcuts 上公開的 UI,將全域指令重新對應到偏好的按鍵組合。

示例:

manifest.json:

{
  "name": "My extension",
  ...
  "commands": {
    "toggle-feature-foo": {
      "suggested_key": {
        "default": "Ctrl+Shift+5"
      },
      "description": "Toggle feature foo",
      "global": true
    }
  },
  ...
}

示例

下列範例展示了 Commands API 的核心功能。

基本指令

指令可讓擴充功能將邏輯對應至使用者可叫用的鍵盤快速鍵。基本上,指令只需要在擴充功能的資訊清單中宣告指令,以及監聽事件監聽器,如以下範例所示。

manifest.json:

{
  "name": "Command demo - basic",
  "version": "1.0",
  "manifest_version": 3,
  "background": {
    "service_worker": "service-worker.js"
  },
  "commands": {
    "inject-script": {
      "suggested_key": "Ctrl+Shift+Y",
      "description": "Inject a script on the page"
    }
  }
}

service-worker.js:

chrome.commands.onCommand.addListener((command) => {
  console.log(`Command "${command}" triggered`);
});

動作指令

如「用量」一節所述,您也可以將指令對應至擴充功能的動作。以下範例會插入內容指令碼,在使用者點選擴充功能的動作或觸發鍵盤快速鍵時,在目前頁面上顯示快訊。

manifest.json:

{
  "name": "Commands demo - action invocation",
  "version": "1.0",
  "manifest_version": 3,
  "background": {
    "service_worker": "service-worker.js"
  },
  "permissions": ["activeTab", "scripting"],
  "action": {},
  "commands": {
    "_execute_action": {
      "suggested_key": {
        "default": "Ctrl+U",
        "mac": "Command+U"
      }
    }
  }
}

service-worker.js:

chrome.action.onClicked.addListener((tab) => {
  chrome.scripting.executeScript({
    target: {tabId: tab.id},
    func: contentScriptFunc,
    args: ['action'],
  });
});

function contentScriptFunc(name) {
  alert(`"${name}" executed`);
}

// This callback WILL NOT be called for "_execute_action"
chrome.commands.onCommand.addListener((command) => {
  console.log(`Command "${command}" called`);
});

確認已註冊指令

如果擴充功能嘗試註冊已有其他擴充功能使用的捷徑,第二個擴充功能的捷徑將無法如預期註冊。您可以預測這種可能性,並在安裝時檢查衝突情形,以提供更優質的使用者體驗。

service-worker.js:

chrome.runtime.onInstalled.addListener((details) => {
  if (details.reason === chrome.runtime.OnInstalledReason.INSTALL) {
    checkCommandShortcuts();
  }
});

// Only use this function during the initial install phase. After
// installation the user may have intentionally unassigned commands.
function checkCommandShortcuts() {
  chrome.commands.getAll((commands) => {
    let missingShortcuts = [];

    for (let {name, shortcut} of commands) {
      if (shortcut === '') {
        missingShortcuts.push(name);
      }
    }

    if (missingShortcuts.length > 0) {
      // Update the extension UI to inform the user that one or more
      // commands are currently unassigned.
    }
  });
}

類型

Command

屬性

  • description

    字串 選用

    擴充功能指令說明

  • 名稱

    字串 選用

    擴充功能指令的名稱

  • 捷徑

    字串 選用

    這個指令的快速鍵有效,如未啟用,則為空白。

方法

getAll()

Promise
chrome.commands.getAll(
  callback?: function,
)

傳回這個擴充功能的所有已註冊擴充功能指令,以及相應的捷徑 (如果已啟用)。在 Chrome 110 之前的版本中,這個指令並未傳回 _execute_action

參數

  • 回呼

    函式選用

    callback 參數如下所示:

    (commands: Command[])=>void

傳回

  • Promise<指令[]>

    Chrome 96 以上版本

    Manifest V3 以上版本支援 Promise,但是為了提供回溯相容性而提供的回呼。您無法在同一個函式呼叫中同時使用這兩者。承諾會用傳遞至回呼的同類型解析。

活動

onCommand

chrome.commands.onCommand.addListener(
  callback: function,
)

使用鍵盤快速鍵啟動已註冊的指令時觸發。

參數

  • 回呼

    功能

    callback 參數如下所示:

    (command: string,tab?: tabs.Tab)=>void

    • Command 鍵

      字串

    • 分頁

      tabs.Tab 選用