11

On hyperlinks in the right click menu, how can I remove or hide the Open In New Tab and Open In New Window options?

for example

<a href="#" onclick="asd">foo</a>
MrCode
  • 63,975
  • 10
  • 90
  • 112
Ashish Arora
  • 227
  • 1
  • 3
  • 4

3 Answers3

24

Not sure why you'd want to do this but it can be done by moving the href to a data-href attribute, then remove the href and add a click handler. The onclick will read the data-href and redirect.

Demo

var links = document.getElementsByTagName("a");

for(var i=0; i<links.length; i++){
    links[i].setAttribute("data-href", links[i].getAttribute("href"));
    links[i].removeAttribute("href");
    links[i].onclick = function(){
        window.location = this.getAttribute("data-href");
    };
}

The right click menu shows:

enter image description here

MrCode
  • 63,975
  • 10
  • 90
  • 112
  • 1
    This is the cleanest option, I concur with Mr Code – box86rowh Jun 18 '13 at 13:02
  • I just googled to this. The reason i'd want to do it is that i have links set up which trigger an ajax action in a modal, and if the user opens them in a new tab then it breaks it (since it's in a new window rather than the modal and doesn't have all the context it needs). Taking the href off is the best solution, i think: i will need to add some extra styling to make them look like links again. – Max Williams Feb 23 '16 at 09:18
2

You can use javascript link instead of plain html ones. Just do href="javascript:void(0)" and handle the click event to redirect the page. This won't remove the option of opening in another tab but will make sure the page doesn't actually open up when tried.

Also instead of an HTML tag, you can instead use another tag like and give it a cursor:pointer css property and jquery onclick to make it work like a link. This will completely remove the option "open in another tab" from context menu.

tornados
  • 86
  • 5
0

you can do it using following code.

<script language="javascript">
$("a").click(function(event)
{
  if(event.button==2)
   {
     return false;    
   }
});
</script>
Anand Shah
  • 611
  • 7
  • 14
  • what do you mean by event.button==2 here ?. Can you please explain I am also trying to stop a link from opening into new tab/window – Vikram Anand Bhushan Oct 06 '14 at 06:12
  • Button 2 stands for second click of the mouse. – Anand Shah Oct 21 '14 at 16:04
  • thanks for the idea, but it should be if(event.which==2) event.which == 1 left click event.which == 2 middle roller click event.which == 3 right click.. I think event.button ==2 for right click from jquery – Learner Mar 17 '15 at 12:29