'Sequencing two action on a button click

Problem: I have a asp.net button and on click of that I am displaying another window using window.open() at the client side using <script></script>

"I actually, need a popup (alert message) to be displayed on my parent page where my button is located once the user closes the child window."

Couple of things I tried are as follows:

  1. I tried using setTimeOut() to have a time out for some milliseconds. This does not work as the control is not waiting until the time out is complete. It just proceeds to execute next set of code.

  2. I tried using setInterval() but for some reason it is not working for me. Below is the code snippet of that:

    $(document).ready(function () {
             $('#<%=btnClick.ClientID%>').bind('click', function () {
                 var newWindow = window.open("http://www.google.com/", "google", 'resizable=1,width=900,height=800,scrollbars=1', '_blank');
                 newWindow.moveTo(0, 0);
                 var test = setInterval(function (e) {
                     if (newWindow.closed) {
                         alert("HEYY");
                         clearInterval(test);
                         __doPostBack("<%= btnClick.UniqueID %>", "");
                     }
                     else {
                         e.preventDefault();
                     }
                 }, 5000);
             });
         });
    

.

  1. I also tried making an ajax call to open the new window and make it async : false, it again did not help me.


Solution 1:[1]

Bring your window and timer variable out of scope of the event handler. You need to do a polling i.e. periodically keep on checking if the windows has been closed. Using setInterval to do a polling will do the job.

var newWin, pollTimer;

$('#btnId').bind('click', function () {
    newWin = window.open("...", "...", "");
    pollTimer = window.setInterval(function() {
        if (newWin.closed) { 
            window.clearInterval(pollTimer);
            callCodeWhenPopupCloses();
        }
    }, 5000);
});

function callCodeWhenPopupCloses() {
    alert("Popup closed.");
    ...
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Abhitalks