How to bypass popup blocker in browser in asynchronous requests

    Problem


    Security policy browsers only allow a pop-up window to be opened if the user has directly taken some action. For example, this code will work:

    $("someElement").on("click", function(){
        window.open("http://yandex.ru")
    }
    


    Now let's say that we need to make an API request to get a link and only after that open a window with this link.
    Thus, the code will no longer work, because the window is already not opened by user action:

    $.get("someURL").done(function(res){
        window.open(res);
    });
    


    Accordingly, it is possible to solve the problem as follows:
    1. Get the desired link in advance, but in this option it is not possible to transfer any parameters according to the user’s action to form the link
    2. make the request synchronous, which is not option
    3. think better

    Third way


    But what if you open a window in advance with an empty link, for usability and eye joy, draw a loading indicator in the window, and after the link is formed, replace the location?

    We try, it works.

    Actually a small piece of code:

     var win = window.open("", params)
    //делаем красивости в win.document или втыкаем адрес открываем не пустую ссылку, а заранее заготовленную на сервере заглушку
    $.get("someURL").done(function(res){
        win.document.location = res;
    });
    


    Other solutions, write in the comments.

    Also popular now: