javascriptwindow.openpopup-blocker

window.open blocked if performed in ajax completed


I have this JS function that is trigger by a click event. It's supposed to store some data and then open a window with an input form. The original code is something like:

function myClickFunction(){
    $('html').mask('Loading...');
    SaveData( function(){ //callback function
        window.open(...);
        $('html').unmask();
    });
}

The problem is that the window.open is blocked by the popup blocker. If I do:

function myClickFunction(){
    $('html').mask('Loading...');
    SaveData();
    $('html').unmask();
    window.open(...);
}

it works just fine but of course I only want to open the window when SaveData() completes.

SaveData() performs an ajax call and in an attempt to make solution #2 work I have tried setting async: false in the ajax call but that just blocks my $('html').mask('Loading...') call.

My setup is similar to https://stackoverflow.com/a/11670238/1480182 but an additional problem is that this has to run on Safari on iPad. And in this particular browser there's no way of making to windows/tabs communicate meaning that when I open the new window I halt any js execution on the opening tab :-(

How should I approach this?


Solution

  • You could open a new window and let it handle the saving and redirect instead of doing it in myClickFunction. The data can be transferred between pages via localstorage.

    So, for example, something like

    function myClickFunction(){
        window.localStorage.tmpData = JSON.stringify(getData());
        window.localStorage.tmpRedirecturl = '...';
        window.open('saveandredirect.html);
    }
    

    And in saveandredirect.html

    $(function(){
        $('html').mask('Loading...');
        var data = JSON.parse(window.localStorage.tmpData);
        var redirecturl = localStorage.tmpRedirecturl;
    
        delete window.localStorage.tmpData; // clear storage
        delete localStorage.tmpRedirecturl;
    
        SaveData(data, function(){
            window.location = redirectUrl;
            $('html').unmask();
        });
    })