【问题标题】:How to prevent default behavior when middle click on a link (browsers' extensions)中键单击链接时如何防止默认行为(浏览器的扩展)
【发布时间】:2017-05-27 07:24:04
【问题描述】:

在我的 Firefox 和 Google Chrome 的扩展程序中,我可以防止中间点击这样的链接时的默认行为:

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?

【问题讨论】:

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2012-05-30
    • 2014-05-30
    • 2011-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-31
    • 2020-07-21
    • 2011-05-12
    相关资源
    最近更新 更多