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"?
Asked
Active
Viewed 1,703 times
2 Answers
1
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>

Michal_Szulc
- 4,097
- 6
- 32
- 59
0
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.

Haris Bouchlis
- 2,366
- 1
- 20
- 35