How to open a URL in a new Tab using JavaScript or jQuery?

JavascriptJqueryasp.net Mvc

Javascript Problem Overview


How to open a URL in new tab instead of new window programatically?

Javascript Solutions


Solution 1 - Javascript

Use window.open():

var win = window.open('http://stackoverflow.com/', '_blank');
if (win) {
    //Browser has allowed it to be opened
    win.focus();
} else {
    //Browser has blocked it
    alert('Please allow popups for this website');
}

Depending on the browsers implementation this will work

There is nothing you can do to make it open in a window rather than a tab.

Solution 2 - Javascript

This is as simple as this.

window.open('_link is here_', 'name'); 

Function description:

name is a name of the window. Following names are supported:

  • _blank - URL is loaded into a new tab. This is default.
  • _parent - URL is loaded into the parent frame
  • _self - URL replaces the current page
  • _top - URL replaces any framesets that may be loaded

Solution 3 - Javascript

if you mean to opening all links on new tab, try to use this jquery

$(document).on('click', 'a', function(e){ 
	e.preventDefault(); 
	var url = $(this).attr('href'); 
	window.open(url, '_blank');
});

Solution 4 - Javascript

 var url = "http://www.example.com";
 window.open(url, '_blank');

Solution 5 - Javascript

You can easily create a new tab; do like the following:

function newTab() {
     var form = document.createElement("form");
     form.method = "GET";
     form.action = "http://www.example.com";
     form.target = "_blank";
     document.body.appendChild(form);
     form.submit();
}

Solution 6 - Javascript

I know your question does not specify if you are trying to open all a tags in a new window or only the external links.

But in case you only want external links to open in a new tab you can do this:

$( 'a[href^="http://"]' ).attr( 'target','_blank' )
$( 'a[href^="https://"]' ).attr( 'target','_blank' )

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMidhunaView Question on Stackoverflow
Solution 1 - JavascriptFabianCookView Answer on Stackoverflow
Solution 2 - JavascriptJaiSatView Answer on Stackoverflow
Solution 3 - JavascriptLafif AstahdziqView Answer on Stackoverflow
Solution 4 - JavascriptcodebreakerView Answer on Stackoverflow
Solution 5 - JavascriptKoffyView Answer on Stackoverflow
Solution 6 - JavascriptDaniel FalabellaView Answer on Stackoverflow