@kyanny's blog

My thoughts, my life. Views/opinions are my own.

Violentmonkey スクリプトをキーボードショートカットで実行する

@violentmonkey/shortcut を使えばできる。

VM.shortcut.register("key sequence", funcName) という形式で関数を登録する。キーシーケンスは複合キー、コンビネーションなどを柔軟に受け付ける。詳細は Key Definition を参照のこと。

Violentmonkey のメニューからも実行できるようにするには、GM_registerMenuCommand と併用すればよい。

GM_registerMenuCommand 経由で呼び出した際は関数の第一引数に MouseEvent オブジェクトが渡される。キーボードショートカットで呼び出した場合は undefined になるので、どちらの方法で呼び出されたか判別できる。

// ==UserScript==
// @name        New script
// @namespace   Violentmonkey Scripts
// @match       *://*/*
// @grant       none
// @grant       GM_registerMenuCommand
// @version     1.0
// @author      -
// @description 4/12/2023, 2:57:38 PM
// @require https://cdn.jsdelivr.net/npm/@violentmonkey/shortcut@1
// ==/UserScript==

const myAlert = (ev) => {
  if (!!ev) {
    alert("Called from menu")
  } else {
    alert("Called from keyboard shortcut")
  }
}

const myConsole = (ev) => {
  if (!!ev) {
    console.log("Called from menu", ev)
  } else {
    console.log("Called from keyboard shortcut", ev)
  }
}

VM.shortcut.register("ctrl-c 1", myAlert)
GM_registerMenuCommand("ctrl-c 1", myAlert)

VM.shortcut.register("ctrl-c 2", myConsole)
GM_registerMenuCommand("ctrl-c 2", myConsole)

xref Violentmonkey スクリプトをポップアップメニューから実行する - @kyanny's blog