Javascript - Open Link in New Tab (SAME WINDOW)

54,094

Solution 1

I have had great success with

<a target='_blank' > 

Solution 2

Using target="_blank" is favourable.

eg. in Chrome, anchors with target="_blank" open a new tab, however, window.open opens a whole new window.

I tried a few experiments to replace window.open with target="_blank".

Blocked by popup blocker

// create an anchor, add to body, trigger click
var a = document.createElement('a');
a.setAttribute('href', 'http://google.com');
a.setAttribute('target', '_blank');
document.body.appendChild(a);
a.click();

// hijack first anchor, change href, trigger click
var a = document.getElementsByTagName('a')[0];
a.setAttribute('href', 'http://google.com');
a.setAttribute('target', '_blank');
a.click();

// hijack first anchor that has target=_blank, change href, trigger click
var a = $('a[target="_blank"]')[0];
a.setAttribute('href', 'http://google.com');
a.click();

Allowed by popup blocker

// hijack first anchor that has target=_blank, change href, next document click triggers it
var a = $('a[target="_blank"]')[0];
a.setAttribute('href', 'http://google.com');
$(document).click(function(){
    $('a[target="_blank"]')[0].click();
});

// create an anchor, add to body, next document click triggers it
var a = document.createElement('a');
a.setAttribute('href', 'http://google.com');
a.setAttribute('target', '_blank');
document.body.appendChild(a);
$(document).click(function(){
    a.click();
});

It seems as long as the popups are triggered by a user interaction, the popup blocker allows it.

Mozilla's documentation on window.open:

https://developer.mozilla.org/en-US/docs/Web/API/window.open

Share:
54,094
A.O.
Author by

A.O.

[email protected]

Updated on August 06, 2022

Comments

  • A.O.
    A.O. over 1 year

    I realize there are a couple questions already on SO for this topic, but they all seem to be quite old....just trying to get an up-to-date answer for this:

    Is the standard way of opening a new tab (within the same browser window) still:

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

    ???

    Also, I've read that it is dependent on the users config of their browser (whether the new page opens in a new tab or a new window, and also whether the new tab/window gets the focus)....I would like the focus to remain on the original tab, but I am more concerned with it opening a tab in the same browser window (keeping focus is just a bonus).

    So is there a way to read/get this setting in new browsers? (chrome, ff, ie) And possibly notify the user to change their settings if they have it set to open in a new window?

  • Serge Stroobandt
    Serge Stroobandt almost 10 years
    The cited jQueryUI link is about adding tabs to a web application inside a browser tab; not about adding a browser tab!
  • Giganticus
    Giganticus almost 10 years
    You know what? You're right. Looking back, I have no idea why I linked to that.