Rene Pot
Rene Pot

Reputation: 24815

How to capture the event when my javascript opened window is closed

The situation is like this. With JavaScript I open a window with a URL on my domain showing a loading indicator.

After about a second, the URL of the window is changed to a PayPal window (so other domain). I want to be able to capture the event when the user closes the paypal window, so I can redirect the user to the correct page saying the payment failed.

I encountered window.onbeforeunload but that one is fired when the url changes to PayPal, but not when the window is closed after that. How do I overcome this issue?

So, this doesn't seem to be working, and I can't find any other answers around here:

    ppwin = window.open('paypal/loading.php', 'paypal_popup', 'width=900,height=500');
    ppwin.onbeforeunload = function(){
        //triggered when URL changes
        if (ppwin.closed) // false because window is still open.
            // Order failed
    }

Even though I accepted the answer, I am still not statisfied with it. It works, but thats it. If someone provides a better answer I would be much more happy!

Upvotes: 1

Views: 3563

Answers (2)

German Latorre
German Latorre

Reputation: 11128

I came accross the same problem and in the end what I did is to make the parent window periodically check if the popup window was closed. Any alternative solution drove me nuts.

The code could be like this:

// Create popup window
var popup = window.open('http://www.google.com');

// Set interval to check if it has been closed
var windowCheckInterval = setInterval(function() { windowCheck(); }, 300);

// Check function
function windowCheck() {
    if (!popup || popup.closed) {
        clearInterval(windowCheckInterval);

        // Do something
    }
}

Despite it is quite a rude solution, user experience is quite good and programming is really simple.

You must remember to clear the interval when process finishes in a different way (not just when the window is closed), it there is any.

Upvotes: 2

roel
roel

Reputation: 2003

see Capture the close event of popup window in JavaScript

You can catch it as long as the pop-up window url is in the same domain as the parent. Otherwise try "the best you could do is open a document in your domain that then loads the remote URL in an iframe, or reads it in via server scripts and renders it from there. "

Upvotes: 0

Related Questions