1

I have a popup made with:

var popup = window.open(URL, ...) //content of popup is not in my control

I want to know when the popup is closed, and thought the below code could help me.

$(popup).unload()

However, Firefox initiates the unload event when the popup appears, not when it's closed!

Is there a reliable way to know when a popup is closed, by the opener?

I don't particularly like polling the popup asking every (say) 500ms if it's closed...

(I found this solution on How to know when popup is closed in javascript)

MFerguson
  • 1,739
  • 9
  • 17
  • 30
Vito De Tullio
  • 2,332
  • 3
  • 33
  • 52

3 Answers3

2

If you can add a onbeforeunload event handler in popup then try something like this,

parent:

function parentCallback(){
  alert("popup is closed");
}

var popup = window.open(URL, ...);

POPUP:

window.onbeforeunload = function(){
    window.opener.parentCallback();
    self.close();
};

else make use of interval, thats what i could suggest, something like

var pop_win = window.open(url,...);   
var timer = setInterval(function() {   
    if(pop_win.closed) {  
        clearInterval(timer);  
        alert('popup is closed');  
    }  
}, 1000);  
dku.rajkumar
  • 18,414
  • 7
  • 41
  • 58
  • OP states having no control of the content in the popup, though – Kyle Macey Jan 17 '12 at 17:56
  • what's the compatibility of the `onbeforeunload` callback? AFAIK it's a ie-nostrict-only thing... – Vito De Tullio Jan 18 '12 at 07:55
  • http://pro-thoughts.blogspot.com/2006/03/onbeforeunload-event.html it is supported by almost all browser. – dku.rajkumar Jan 18 '12 at 08:15
  • You're the only one who mentioned `windowRef.closed`, you get my vote. He didn't want to do polling, but unfortunately it seems impossible to do this correctly without doing so. https://developer.mozilla.org/en-US/docs/Web/API/Window/closed – Chinoto Vokro Feb 19 '16 at 23:14
0

It seems popup.location will return null if it's closed and an empty set if it's open.

popup.location // Open Window

=> Location 
      No Properties Defined

popup.location // Closed Window

=> null

Test with:

if (popup.location) {alert('hello')}
Kyle Macey
  • 8,074
  • 2
  • 38
  • 78
-1

I know this question is a bit old, but for others searching for the answer I think I have found a solution:

You might be able to do like this (it has worked for me anyway, also in FF):

Parent:

var popup = window.open("about:blank"); // Or whatever page you are loading
popup.onunload = function(){
    parent.location.reload();
        // or
    parent.alert("Popup closed!");
        // or any other handler in the parent window,
        // just remember to call it on the parent object.
};
M_Nyby
  • 7
  • 2
  • Where you say `parent`, I'm pretty sure you meant `window`. `window` shouldn't change based on function context, only `this` does that as far as I'm aware. – Chinoto Vokro Feb 19 '16 at 23:18