8

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?

A.O.
  • 3,733
  • 6
  • 30
  • 49

2 Answers2

12

I have had great success with

<a target='_blank' > 
Fabio Milheiro
  • 8,100
  • 17
  • 57
  • 96
Giganticus
  • 246
  • 2
  • 5
9

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

Mike Causer
  • 8,196
  • 2
  • 43
  • 63