3テラバイト

プログラム関連備忘録サイト。主にゲーム。

Chrome拡張

Chrome拡張にキーボードショートカットを追加するcommandsAPIの使い方

投稿日:

こんにちは、今日はChrome拡張にキーボードショートカットを追加するcommandsAPIの使い方についてまとめていきます。

確認環境

Google Chrome バージョン: 87.0.4280.141

commandsAPIの使い方

manifest.json

commandsにキーボードショートカットの設定を追加します。
ここでは「test1」というコマンドを「Ctrl+Shift+1」キーで実行、
「test2」というコマンドを「Ctrl+Shift+2」キーで実行するように設定します。

キーの組み合わせには必ず「Ctrl」または「Alt」を含める必要があり、含まれていない組み合わせがあった場合はmanifest読み込み時にエラーが出ます。

{
  "name": "Sample",
  "version": "1.0",
  "description": "Sample Extension",
  "manifest_version": 2,
  "background" : {
    "scripts": ["background.js"],
    "persistent": false
  },
  "commands": {
    "test1": {
      "suggested_key": {
        "default": "Ctrl+Shift+1"
      },
      "description": "test1"
    },
    "test2": {
      "suggested_key": {
        "default": "Ctrl+Shift+2"
      },
      "description": "test2"
    }
  }
}

background.js

manifestで設定したコマンドの実際の処理を記述していきます。

chrome.commands.onCommandのコールバック関数で実行されたコマンド名が渡されるため、その値から実行コマンドを判定、その処理を実行していきます。

この例では「test1」が実行された場合に「test1 command exec」という内容のアラートを表示、
「test2」が実行された場合に「test2 command exec」という内容のアラートを表示しています。

chrome.commands.onCommand.addListener(function (command) {
  if (command === 'test1') {
    alert("test1 command exec");
  } else if (command === 'test2') {
    alert("test2 command exec");
  }
});

リンク

chrome.commands – Chrome Developers
https://developer.chrome.com/docs/extensions/reference/commands/

-Chrome拡張


comment

メールアドレスが公開されることはありません。

関連記事

no image

Chrome拡張の作り方

ドキュメント 以下のページにChrome拡張開発の入門ページがあります。 Getting started – Chrome Developershttps://developer.chro …

no image

Chrome拡張のソースコード確認方法

以下のディレクトリにて確認したいChrome拡張のIDに対応するフォルダを確認すると、中にソースコードが格納されています。 C:\Users\ユーザー名\AppData\Local\Google\Ch …

no image

Chrome拡張でポップアップを表示する

こんにちは、今日はChrome拡張でポップアップを表示する方法についてまとめていきます。 確認環境 Google Chrome バージョン: 87.0.4280.141 browser_action …