DEV Community

Digvijay Singh
Digvijay Singh

Posted on

How to Open a New Tab or Window using Javascript?

It is a very general use case to open a link in another tab or in a separate window. We prefer to use target="_blank" attribute in HTML to open a link in new tab.

Sometimes we need to open a link in new tab only by javascript. Here are the code snippets to open a link in a new tab or new window by pure Vanilla Javascript.

Open New Tab Using Javascript

 window.open("https://holycoders.com/", "_blank", "noopener")
Enter fullscreen mode Exit fullscreen mode

The open method is very useful to open a new tab or window in the browser.

Open New Window Using Javascript

 window.open('https://holycoders.com', '_blank', 'noopener,height=600,width=960,scrollbars=yes'); 
Enter fullscreen mode Exit fullscreen mode

Let me warn you that it is very annoying and never recommended to open a new window on the user's system just for your own purpose (I am talking about those ads).
If you liked this article you will also like Pure Javascript Modal

Top comments (6)

Collapse
 
isarisariver profile image
Marian

Great post. In case you are not aware, it can be a security risk to use window.open with _blank without rel="noopener noreferrer" (explained for example here mathiasbynens.github.io/rel-noopener/ )

Collapse
 
digvijaysingh profile image
Digvijay Singh • Edited

Thanks for this amazing information. I am right now exploring with web security and this is really very helpful.

Updated the Post.

Collapse
 
vikasjk profile image
Vikas-jk • Edited

Thanks, You can also try this as some browser block this pop-up, so you can have this

   var win = window.open('https://google.com/', '_blank');
   if (win) {
     //Browser allows the new tab to open
     win.focus();
   } else {
     //Browser has blocked it
     alert('Please allow popups for this website');
  }
Enter fullscreen mode Exit fullscreen mode

Source : How to open New tab using javascript or jquery and open href in it?

Collapse
 
winstonpuckett profile image
Winston Puckett

Really concise. I'll have to remember this post the next time I need this :)

Collapse
 
codeperfectplus profile image
Deepak Raj

but it helpful for some sites like net banking.

Collapse
 
digvijaysingh profile image
Digvijay Singh

Yes, and also popular for Oauth logins without losing state.