あしあと

自分自身のログ(足跡)となります。ソフトウェアエンジニアです。ブログはテック系の内容が少し多めです。

Electronで場所によって右クリックの表示を変更する方法

Electronで場所によって右クリックの表示を変更する方法です。

結論

右クリックのカスタマイズはElectronが特別ではなく、Javascriptの仕様です。
ブラウザの右クリックの挙動はContext​Menusで変更することが可能です。

developer.mozilla.org

これは、Elementオブジェクトに対して設定するので、Elementオブジェクトごとに設定をすれば良いです。

サンプルコード

レンダラープロセス側のJavaScriptです。

const remote = require('electron').remote;

/** 1つ目の設定 */
let menuA = new remote.Menu();
menuA.append(new remote.MenuItem({role: 'copy', accelerator: 'Cmd+C'}));
let a = document.getElementById('menuA');
a.addEventListener('contextmenu', function (e) {
  e.preventDefault();
  menuA.popup();
}, false);


/** 2つ目の設定 */
let menuB = new remote.Menu();
menuB.append(new remote.MenuItem({role: 'paste', accelerator: 'Cmd+P'}));
let b = document.getElementById('menuB');
b.addEventListener('contextmenu', function (e) {
  e.preventDefault();
  menuB.popup();
}, false);

あとは、HTMLで以下のように設定するとOKです。

<div id='menuA'>
  MenuA
</div>

<div id='menuB'>
  MenuB
</div>

以下のように動作します。

f:id:pyo_hei:20190609082135g:plain

最後に

私はElectronでアプリを作成していたので、Electronをベースに検索して見つからず、困りました。
なので、Electronから検索できるよう、今回書きました。

JavaScript単体での右クリックの制御は検索すれば割とでます。