Struggler
Struggler

Reputation: 682

Programmatically opening a new tab within a callback

I am looking to open a new tab, programmatically, in the callback of a save operation. Not very different from http://jsfiddle.net/5Lwwmbq8/1/

var atag = document.createElement('a');
atag.setAttribute('href', 'https://yahoo.com');
atag.setAttribute('target', '_blank');
atag.setAttribute('id','clickdamnit');
$('#onlydiv').append(atag);
setTimeout(function() {
    atag.click();
}, 3000);

If I don't put it within a callback everything works fine. But within the confines of the callback, it is blocked by a pop up blocker. Is there a way around this?

I have tried substituting the anchor tag by window.open - same result.

Upvotes: 1

Views: 1892

Answers (1)

Struggler
Struggler

Reputation: 682

I was able to hack my way around by serving a intermediate page (say '/sameDomainDummySpinnerPage') and then redirecting in the callback.

$('#linktest').click(function(){
    var childWindow = window.open('/sameDomainDummySpinnerPage');
    setTimeout(function() {
        childWindow.location.replace('http://yahoo.com');
    }, 3000);
});

Another way around that I came upon was setting the 'target' attribute to a unique string. In the callback window.open on the same target affects the previously introduced tab. But this leads to a deteriorated user experience. The user may use the tab, your script opened, to surf the web. On re-running, your script will: 1. override tab's existing window.location 2. may not allow .focus(); causing the user to miss out on the response of their action

ref: https://developer.mozilla.org/en-US/docs/Web/API/Window.open#Do_not_use_target.3D.22_blank.22 http://www.infimum.dk/HTML/JSwindows.html Bypass popup blocker on window.open when JQuery event.preventDefault() is set

Upvotes: 2

Related Questions