javascript window.open from callback

zardoz picture zardoz · Sep 26, 2013 · Viewed 16.2k times · Source

window.open() called from main thread opens new tab by default.

But, here open new window every time (Opera 16 and Google Chrome 29)

<input type="button" value="Open" onclick="cb1()">

<script type="text/javascript">  
function cb1() {
    setTimeout(wo, 1000); //simple async
}

function wo()
{
   var a = window.open("http://google.com", "w2");
   a.focus();
}
</script>

(lol, this is my answer for Open a URL in a new tab (and not a new window) using JavaScript).

How I can open in the tab (by browser default) here?

Answer

Yogh picture Yogh · Mar 18, 2014

We ran across this same problem and hunted around SO for an answer. What we found works in our circumstances and the distilled wisdom is as follows:

The problem is related to browser pop-up blockers preventing programmatic window opens. Browsers allow window opens from actual user clicks which occur on the main thread. Similarly, if you call window.open on the main thread it will work, as noted above. According to this answer on Open a URL in a new tab (and not a new window) using JavaScript if you are using an Ajax call and want to open the window on success you need to set async: false which works because that will keep everything on the main thread.

We couldn't control our Ajax call like that, but found another solution that works because of the same reasons. Warning, it is a bit hacky and may not be appropriate for you given your constraints. Courtesy of a comment on a different answer on Open a URL in a new tab (and not a new window) using JavaScript you open the window before calling setTimeout and then update it in the delayed function. There are a couple of ways of doing this. Either keep a reference to the window when you open it, w = window.open... and set w.location or open with a target, window.open('', 'target_name'), in the delayed function open in that target, window.open('your-url', 'target_name'), and rely on the browser keeping the reference.

Of course, if the user has their settings to open links in a new window this isn't going to change that, but that wasn't a problem for the OP.