Javascript 右键单击并选择其中一项后,从上下文菜单中替换href链接;“打开…”;

Javascript 右键单击并选择其中一项后,从上下文菜单中替换href链接;“打开…”;,javascript,html,hyperlink,href,contextmenu,Javascript,Html,Hyperlink,Href,Contextmenu,我可以进入contextmenu对象并禁用它(),但当用户右键单击链接对象并选择“在新选项卡中打开”或“在新窗口中打开”或“在匿名窗口中打开”时,我如何替换链接对象中的原始href呢?在我看来,出于安全原因,您无法这样做。要与上下文菜单交互,您可以签出此库 编辑:你可以试试这个,尽管它有点粗糙 <html> <head> </head> <body> <a href="http://www.google.com">Google</

我可以进入contextmenu对象并禁用它(),但当用户右键单击链接对象并选择“在新选项卡中打开”或“在新窗口中打开”或“在匿名窗口中打开”时,我如何替换链接对象中的原始href呢?

在我看来,出于安全原因,您无法这样做。要与上下文菜单交互,您可以签出此库

编辑:你可以试试这个,尽管它有点粗糙

<html>
<head>
</head>
<body>
<a href="http://www.google.com">Google</a>
<script>

    // get all anchor elements
    var anchors = document.getElementsByTagName("a");

    for(var i=0; i<anchors.length; i++){
        var el = anchors[i];

        // add event listener on each anchor element
        el.addEventListener('contextmenu', function(ev) {

            // get the original href value of the element
            var originalTarget = el.href;

            // change it to what you want to go to
            el.href = 'http://www.amazon.com';

            // asynchonously change it back to the original
            setTimeout(function(){
                el.href = originalTarget;
            },1);
        }, false);
    }

</script>
</body>
</html>

//获取所有锚元素
var archors=document.getElementsByTagName(“a”);

对于(var i=0;i事实上,我找到了一种更好/更简单的方法来实现它。replaceLink()负责替换以下菜单链接:

<html>
   <head>
      <meta charset="utf-8"/>
   </head>
   <body>
      <a href="https://majkesz.pl" id="lol" oncontextmenu="replaceLink(event);">majkesz.pl</a><br>
      <script>
     document.getElementById("lol").onclick = function(event) {
        event.preventDefault();
        window.location.href = "https://www.youtube.com/watch?v=oHg5SJYRHA0";
        return false;
        };


     function replaceLink(e) {
     e.target.href = "https://www.youtube.com/watch?v=oHg5SJYRHA0";

     }
      </script>
   </body>
</html>


document.getElementById(“lol”).onclick=函数(事件){ event.preventDefault(); window.location.href=”https://www.youtube.com/watch?v=oHg5SJYRHA0"; 返回false; }; 函数替换链接(e){ e、 target.href=”https://www.youtube.com/watch?v=oHg5SJYRHA0"; }
不幸的是,对于FF和更新的chrome,上述解决方案不适用于鼠标中键单击。请改用通用:

<html>
   <head>
      <meta charset="utf-8"/>
   </head>
   <body>
      <a href="https://majkesz.pl" onmousedown="replaceLink(event)" oncontextmenu="replaceLink(event);">majkesz.pl</a><br>
      <script>
     function replaceLink(e) {
     e.target.href = "https://www.youtube.com/watch?v=oHg5SJYRHA0";

     }
      </script>
   </body>
</html>


函数替换链接(e){ e、 target.href=”https://www.youtube.com/watch?v=oHg5SJYRHA0"; }