Replace href link from contextmenu after right-cli

2019-08-20 00:30发布

I can get into contextmenu object and disable it (How to add a custom right-click menu to a webpage?), but how can I replace original href from a link object, when user right-click on it and choose "open in a new tab" or "open in a new window" or "open in an incognito window"?

2条回答
干净又极端
2楼-- · 2019-08-20 00:55

It seems to me that you wouldn't be able to do that for security reasons. For interacting with the context menu you can check out this library http://ignitersworld.com/lab/contextMenu.html.

EDIT: You can try this, although its a little hacky.

<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>

it adds an event listener on all anchor elements and changes the href when the context menu event is fired, and after that it changes it back to its original value. Hope it works for you.

查看更多
倾城 Initia
3楼-- · 2019-08-20 01:18

In fact I found a better/simpler way to achieve it. replaceLink() is responsible for replacing centextmenu links here:

<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>

unfortunatelly above solution is not working for middle click of mouse for FF and newer chrome. instead use generic:

<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>
查看更多
登录 后发表回答