Open a URL in a new tab (and not a new window)

I'm trying to open a URL in a new tab, as opposed to a popup window.

I've seen related questions where the responses would look something like:

window.open(url,'_blank');
window.open(url);

But none of them worked for me, the browser still tried to open a popup window.


Solution 1:

This is a trick,

function openInNewTab(url) {
 window.open(url, '_blank').focus();
}

//or just
window.open(url, '_blank').focus();

In most cases, this should happen directly in the onclick handler for the link to prevent pop-up blockers, and the default "new window" behavior. You could do it this way, or by adding an event listener to your DOM object.

<div onclick="openInNewTab('www.test.com');">Something To Click On</div>

http://www.tutsplanet.com/open-url-new-tab-using-javascript/

Solution 2:

Nothing an author can do can choose to open in a new tab instead of a new window; it is a user preference. (Note that the default user preference in most browsers is for new tabs, so a trivial test on a browser where that preference hasn't been changed will not demonstrate this.)

CSS3 proposed target-new, but the specification was abandoned.

The reverse is not true; by specifying certain window features for the window in the third argument of window.open(), you can trigger a new window when the preference is for tabs.

Solution 3:

window.open() will not open in a new tab if it is not happening on the actual click event. In the example given the URL is being opened on the actual click event. This will work provided the user has appropriate settings in the browser.

<a class="link">Link</a>
<script  type="text/javascript">
     $("a.link").on("click",function(){
         window.open('www.yourdomain.com','_blank');
     });
</script>

Similarly, if you are trying to do an Ajax call within the click function and want to open a window on success, ensure you are doing the Ajax call with the async : false option set.

Solution 4:

function openInNewTab(href) {
  Object.assign(document.createElement('a'), {
    target: '_blank',
    href: href,
  }).click();
}

It creates a virtual a element, gives it target="_blank" so it opens in a new tab, gives it proper url href and then clicks it.

and then you can use it like:

openInNewTab("https://google.com"); 

Important note:

openInNewTab (as well as any other solution on this page) must be called during the so-called 'trusted event' callback - eg. during click event (not necessary in callback function directly, but during click action). Otherwise opening a new page will be blocked by the browser

If you call it manually at some random moment (e.g., inside an interval or after server response) - it might be blocked by the browser (which makes sense as it'd be a security risk and might lead to poor user experience)