中间点击链接时如何防止默认行为(浏览器'扩展名)

时间:2017-05-27 07:24:05

标签: javascript google-chrome firefox microsoft-edge microsoft-edge-extension

在我的Firefox&谷歌浏览器的扩展我可以在中间点击这样的链接时阻止默认行为:

function onClick(e) {
    var url = getLink(e);
    if (e.button == 1) { // Middle Click
        // prevent opening a link
        e.preventDefault();
        e.stopPropagation();
        // do something with a link
        // url ...
    }
}
if (browser == "chrome")
    document.addEventListener("auxclick", onClick); // for Google Chrome (old "click" event doesn't prevent opening link with middle click but they added "auxclick" for this)
else if (browser == "firefox") 
    document.addEventListener("click", onClick); // for Firefox (still works)

https://developers.google.com/web/updates/2016/10/auxclickhttps://developer.mozilla.org/en-US/docs/Web/Events/auxclick

我也尝试为我的Microsoft Edge扩展程序执行此操作,但此浏览器的中间点击事件似乎根本不起作用:

function onClick(e) {
    var url = getLink(e);
    if (e.button == 1) { // Middle Click
        alert("hello"); // isn't working for Microsoft Edge
    }
}
document.addEventListener("click", onClick);

因此,对于Microsoft Edge而言,我使用:

document.addEventListener("mousedown", function(e) {
    var target = e.target || e.srcElement;
    while (target) {
        if (target instanceof HTMLAnchorElement)
            break;
        target = target.parentNode;
    }
    if (e.button == 1 && target.href != null) {
        alert("hello"); // works when middle click on a link
        // but these preventing doesn't works here:
        e.preventDefault();
        e.stopPropagation();
        // link will still be opened in a new tab
    }
});

但是,当中间点击

时,此方法不会阻止在新标签页中打开链接

如何让Microsoft Edge像Google Chrome或Firefox一样?

1 个答案:

答案 0 :(得分:0)

似乎最新版本的 Edge 现在有事件监听器 auxclick,和 Chrome 一样,因为 Edge 现在基于 Chromium 引擎,而不是 EdgeHTML