0

できればjavascriptで制御したいのですが、どのようにすればよいでしょうか?

1 件の回答 1

1

何の機能を禁止するかにも依るようですが、一般的な「新しいタブでリンクを開く」機能を禁止する場合には、auxclick イベントMouseEvent.button1 のものを抑止すれば良いようです。

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 を用いて実装されていることがありますが、もしかするとこれらのブラウザではこちらが利用できるかもしれません(※環境が無いので私は試せていません)。)


それ以外の機能、オートスクロールやクリップボードペースト機能の禁止は mousedownpointerdown で行うようです。

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 or pointerdown event.

1
  • ご丁寧なご回答ありがとうございます。質問に具体的な内容が無くすみません。a linkだけではなく、divタグでも問題なく稼働しました。videoタグで表示している動画をホイールクリックした場合、新規ウィンドウで開いてしまうことを禁止したかったので助かりました。あとはIE, Safari問題も解決したいところです。。。
    – stag
    2021年10月6日 12:31

この質問に回答するには、ログインする必要があります。

求めていた回答ではありませんか? のタグが付いた他の質問を参照する。