Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/apache/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何防止鼠标中键单击链接时出现默认行为(浏览器扩展名)_Javascript_Google Chrome_Firefox_Microsoft Edge_Microsoft Edge Extension - Fatal编程技术网

Javascript 如何防止鼠标中键单击链接时出现默认行为(浏览器扩展名)

Javascript 如何防止鼠标中键单击链接时出现默认行为(浏览器扩展名),javascript,google-chrome,firefox,microsoft-edge,microsoft-edge-extension,Javascript,Google Chrome,Firefox,Microsoft Edge,Microsoft Edge Extension,在我的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 somet

在我的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)
而且

我也尝试为我的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现在基于Chrome引擎,而不是EdgeHTML

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

尝试使用onmouseup而不是onmousedown。@Robbarsons在Microsoft站点上创建此问题没有区别:尝试使用onmouseup而不是onmousedown。@Robbarsons在Microsoft站点上创建此问题没有区别: