Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable the 'Open Link in New Tab' in the browser?

How do I disable/remove the 'Open Link in New Tab' option in the right-click menu of the browser? If this is not possible with javascript etc then is there a way to modify what happens when the user clicks on this link, for example, display an alert or prevent the tab from loading..?

like image 929
grai Avatar asked Aug 10 '11 05:08

grai


1 Answers

The ability to open a link in a new tab/window is native functionality of many browsers. If you do not wish to allow this type of activity, then you need to notify the browser that your link is not truly a link. The easiest way to do so is to remove the href attribute from your a element.

HTML:

<a href="http://google.com">Can be opened in new tab/window</a>
<a>Cannot be opened in new tab/window</a>

Now there are some other things that the browser may be doing for you by default when it sees a link. If you have not defined any styling of a elements, it's likely that your new fancy pseudo-link will not appear with a link font-color, pointer, and underline. You can go ahead and do that easily enough.

CSS:

a {
    color: blue;
    cursor: pointer;
    text-decoration: underline;
}

That hopefully answers the question of how you disable/remove the 'Open Link in New Tab' option in the right-click menu of the browser. For some extra credit though I'm going to assume that you probably want the link to still function like a regular link when clicked. Feel free to use some JavaScript to make that happen. Here's an example using jQuery:

JavaScript:

$("body").on("click", "a[data-href]", function() {
    var href = $(this).data("href");
    if (href) {
        location.href = href;
    }
});

Modified Html:

<a href="http://google.com">Can be opened in new tab/window</a>
<a data-href="http://google.com">Cannot be opened in new tab/window</a>

Modified CSS:

a[href], a[data-href] {
    color: blue;
    cursor: pointer;
    text-decoration: underline;
}

Hope this helps!

like image 119
Phil Klein Avatar answered Oct 17 '22 15:10

Phil Klein