LoginSignup
20

More than 5 years have passed since last update.

Chrome App/Extensions で特殊キーの入力やキーボードショートカットを受け取る

Posted at

巷で流行りのGoogle Play Music、これのChromeアプリにはメディアキー( :rewind: :arrow_forward: :fast_forward: のような)を入力すれば(たとえアプリや拡張機能がバックグラウンドでしか動作していなくても)どこにいても再生をコントロールできる神機能が搭載されている。
ちなみにこのキーは通常のkeydownのイベントリスナーでは拾えないっぽい。

実装方法とか知らなかったんで例のアプリのmanifest.jsonを覗いてみたら答えは一瞬で出た。

commands で実装

決して最近できたものではなく、昔から(Chrome 25から)利用できるchrome.commandsを使う。
日本語で書いてる記事少ないっぽいけど使ってる人は結構いるはず
chrome-extension - キーの入力だけで目的のタブに素早く切り替えられる Google Chrome 拡張つくりました - Qiita

どう使うの

manifest.jsonにcommandsのセッションを追加する

以下はGoogle Play Musicのそれより抜粋

manifest.json
{
...
   "commands": {
      "next-track": {
         "description": "next track",
         "global": true,
         "suggested_key": {
            "default": "MediaNextTrack"
         }
      },
      "play-pause": {
         "description": "play/pause",
         "global": true,
         "suggested_key": {
            "default": "MediaPlayPause"
         }
      },
      "previous-track": {
         "description": "previous track",
         "global": true,
         "suggested_key": {
            "default": "MediaPrevTrack"
         }
      },
      "stop": {
         "description": "stop playback",
         "global": true,
         "suggested_key": {
            "default": "MediaStop"
         }
      }
   },
...
}
"コマンド名": {
  "description": "コマンドの説明",
  "global": true, // Chromeが非アクティブな時にも拾うか? *** Chrome35+ ***
  "suggested_key": { // キーパターン
              "default": "Ctrl+Shift+Y",
              "windows": "Ctrl+Shift+Y",
              "mac": "Command+Shift+Y",
              "chromeos": "Ctrl+Shift+U",
              "linux": "Ctrl+Shift+J"
  }
},
...

のようなフォーマットで書いておく。

キーパターンは一般キーは上記のよう、ほかに以下のような特殊キー等。

Comma, Period, Home, End, PageUp, PageDown, Space, Insert, Delete, Arrow keys (Up, Down, Left, Right) and the Media Keys (MediaNextTrack, MediaPlayPause, MediaPrevTrack, MediaStop).

あとMacではCtrlCommandに自動置換されるのでCtrlのままにするにはMacCtrlにしろだとかChromeOSではSearchがあるだとかあるらしいので詳しくはdocument参照。

これで 設定の 拡張機能 > キーボードショートカット に以下のような感じに追加される。
image

登録されたコマンドはアプリ・拡張機能からchrome.commands経由で取得したり拾ったりできる。

一覧: chrome.commands.getAll
image

リスナー追加: chrome.commands.onCommand.addListener
image
(入力時にコールバックにコマンド名が返される)

これでバックグラウンドで再生中のPlay Musicのなうぷれとか実装できないかな?

参考

chrome.commands - Google Chrome

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20