Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect to a new tab within javascript file

I have code that sets:

top.location.href = [someurl] 

But I want it to open up in a new tab. Is there anyway to have the above code include: target="_blank"?

like image 816
Elizabeth Bradley Avatar asked Aug 15 '14 17:08

Elizabeth Bradley


People also ask

How do I redirect a link in a new tab?

You just need an anchor ( <a> ) element with three important attributes: The href attribute set to the URL of the page you want to link to. The target attribute set to _blank , which tells the browser to open the link in a new tab/window, depending on the browser's settings.

Can redirection of a page is possible in JavaScript?

It is quite simple to do a page redirect using JavaScript at client side. To redirect your site visitors to a new page, you just need to add a line in your head section as follows.

Can you make the link open in a new tab JavaScript?

You need to use the _blank value in the target attribute to open the linked URL in a new tab or window. If you want to open URL with JavaScript, the open() method of Window interface is the best option. The JavaScript window. open() method opens a new browser window.


2 Answers

Use the method window.open(url, target) to open a new window (it depends on the browser or the user's settings whether the URL is opened in a new window or tab):

window.open('http://stackoverflow.com', '_blank'); 

For more information about window.open(), read the documentation at w3schools.

Please note: Randomly opening a new window (or tab) isn't allowed in most browsers, because it is then treated as an "unwanted popup".

like image 158
lvogel Avatar answered Sep 19 '22 22:09

lvogel


If you're doing this in response to a user's action (such as a click), you can use window.open:

window.open("someurl", "_blank"); 

On most browsers with default settings, that will open a new tab rather than a new window. The user is, of course, in charge and can change the settings so it's a new window instead.

You cannot do this with a decent browser if it's not in response to a user's click, so that web pages cannot open tabs randomly.

like image 27
T.J. Crowder Avatar answered Sep 18 '22 22:09

T.J. Crowder