Javascript detect closing popup loaded with another domain

As mentioned, same origin policy prevents Javascript from detecting such events. But there’s a quite simple solution which allows you to detect closure of such windows.

Here’s the JS code:

var openDialog = function(uri, name, options, closeCallback) {
    var win = window.open(uri, name, options);
    var interval = window.setInterval(function() {
        try {
            if (win == null || win.closed) {
                window.clearInterval(interval);
                closeCallback(win);
            }
        }
        catch (e) {
        }
    }, 1000);
    return win;
};

What it does: it creates new window with provided parameters and then sets the checker function with 1s interval. The function then checks if the window object is present and has its closed property set to false. If either ot these is not true, this means, that the window is (probably) closed and we should fire the ‘closeCallback function’ callback.

This function should work with all modern browsers. Some time ago Opera caused errors when checking properties from windows on other domains – thus the try..catch block. But I’ve tested it now and it seems it works quite ok.

We used this technique to create ‘facebook-style’ login popups for sites which doesn’t support them via SDK (ehem… Twitter… ehem). This required a little bit of extra work – we couldn’t get any message from Twitter itself, but the Oauth redireced us back to our domain, and then we were able to put some data in popup window object which were accessible from the opener. Then in the close callback function we parsed those data and presented the actual results.

One drawback of this method is that the callback is invoked AFTER the window has been closed. Well, this is the best I was able to achieve with cross domain policies in place.

Leave a Comment