できればjavascriptで制御したいのですが、どのようにすればよいでしょうか?
1 件の回答
何の機能を禁止するかにも依るようですが、一般的な「新しいタブでリンクを開く」機能を禁止する場合には、auxclick
イベント で MouseEvent.button
が 1
のものを抑止すれば良いようです。
Element: auxclick event > Preventing default actions:
For the vast majority of browsers that map middle click to opening a link in a new tab, including Firefox, it is possible to cancel this behavior by calling
preventDefault()
from within an auxclick event handler.
link.addEventListener("auxclick", (e) => {
if (e.button === 1) {
console.log("middle button clicked");
e.preventDefault();
}
});
<html>
<body>
<a href="https://ja.stackoverflow.com/" id="link">スタック・オーバーフロー</a>
</body>
</html>
ただしMDNの説明にもある通り、IE, Safariでは auxclick
イベントが実装されておらず想定通り動作しません。
(古い説明(例)では click
イベントと MouseEvent.which === 2
を用いて実装されていることがありますが、もしかするとこれらのブラウザではこちらが利用できるかもしれません(※環境が無いので私は試せていません)。)
それ以外の機能、オートスクロールやクリップボードペースト機能の禁止は mousedown
や pointerdown
で行うようです。
When listening for auxclick events originating on elements that do not support input or navigation, you will often want to explicitly prevent other default actions mapped to the down action of the middle mouse button. On Windows this is usually autoscroll, and on macOS and Linux this is usually clipboard paste. This can be done by preventing the default behavior of the
mousedown
orpointerdown
event.