javascript阻止鼠标中键打开新选项卡中的链接

javascript prevent middle mouse button from opening link in new tab

本文关键字:选项 链接 鼠标中键 新选项 javascript      更新时间:2023-09-26

在一些网站上,您可以右键单击链接并选择"在新选项卡中打开",这很好,但如果使用鼠标中键则不行。我遇到过几次这种情况,这并不太烦人,但我仍然很好奇是什么导致了这种行为。(关于如何)以下是一个使用Chrome 46进行浏览的网站:http://ebookfriendly.com/free-public-domain-books-sources/html链接标签看起来很正常:

<a title="Feedbooks" href="http://www.feedbooks.com/">⇢ Feedbooks</a>

原因一定是javascript中的某些内容。有指针吗?

执行此操作的一种方法是使用auxclick事件。(点击MDN)

以下代码将防止在整个页面上出现鼠标中键单击行为。

window.addEventListener("auxclick", (event) => {
  if (event.button === 1) event.preventDefault();
});

这个链接似乎有一个使用preventDefault()并通过其他方式打开页面的事件侦听器。

编辑:很难说他们为什么这么做,但当我查看整个处理程序时,链接似乎被传递到了谷歌分析:

function(e) {
    var n = this.getAttribute("href"),
        i = "string" == typeof this.getAttribute("target") ? this.getAttribute("target") : "";
    ga("send", "event", "outbound", "click", n, {
        hitCallback: t(n, i)
    }, {
        nonInteraction: 1
    }), e.preventDefault()
}

您可以询问是哪个按钮导致了事件并阻止默认行为。

document.querySelector("a").addEventListener("click", function(e) { 
   if (e.which === 2) {
      e.preventDefault();
   } 
}, false);
    $(document).mousedown(function(e){
        if(e.which == 2 ){
            e.preventDefault();
            alert("middle click");   
            return false;
        }
    });

只有当您保持alert()时才有效