Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript detect closing popup loaded with another domain

I am opening a popup window and attaching an onbeforeunload event to it like this:

win = window.open("http://www.google.com", "", "width=300px,height=300px");
win.onbeforeunload = function() {
    //do your stuff here
    alert("Closed");
};

If I leave the URL empty, the new popup opens with "about:blank" as the address but when I close it, I see the alert.

If I open in as you see it (with an external URL), once it's closed, I cannot see the alert anymore. Any idea why this is happening?

like image 429
Zorrocaesar Avatar asked Mar 29 '13 00:03

Zorrocaesar


4 Answers

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.

like image 58
Tomasz Struczyński Avatar answered Oct 23 '22 19:10

Tomasz Struczyński


You could listen to the 'focus' event of the opener window which fires when the user closes the popup.

like image 27
Andrew Avatar answered Oct 23 '22 19:10

Andrew


Unfortunately, you're trying to communicate across domains which is prohibited by JavaScript's same origin policy. You'd have to use a server-side proxy or some other ugly hack to get around it.

You could try creating a page on your site that loads the external website in an iframe. You could then pop open that page and listen for it to unload.

like image 1
chrx Avatar answered Oct 23 '22 19:10

chrx


I combined @ThomasZ's answer with this one to set an interval limit (didn't want to use setTimeout).

Example (in Typescript, declared anonymously so as not lose reference to "this"):

  private _callMethodWithInterval = (url: string, callback: function, delay: number, repetitions: number) => {      
    const newWindow = window.open(url, "WIndowName", null, true);

    let x = 0;
    let intervalID = window.setInterval(() => {
      //stops interval if newWindow closed or doesn't exist
      try {
        if (newWindow == null || newWindow.closed) {
          console.info("window closed - interval cleared")
          callback();
          window.clearInterval(intervalID);
        }
      }
      catch (e) {
        console.error(`newWindow never closed or null - ${e}`)
      }
      //stops interval after number of intervals
      if (++x === repetitions) {
        console.info("max intervals reached - interval cleared")        
        window.clearInterval(intervalID);
      }
    }, delay)
  }//end _callMethodWithInterval  
like image 1
barakbd Avatar answered Oct 23 '22 21:10

barakbd