如何防止中键单击链接时的默认行为(浏览器的扩展)



在我的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/auxclick,https://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?

似乎最新版本的Edge现在

具有事件侦听器auxclick,与Chrome相同,因为Edge现在基于Chromium引擎,而不是EdgeHTML

相关内容

  • 没有找到相关文章

最新更新