在我的 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?