Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
155
rated 0 times [  158] [ 3]  / answers: 1 / hits: 97118  / 14 Years ago, tue, july 20, 2010, 12:00:00

The question is pretty much all in the title.



Is it possible (and how?) to open a popup with javascript and then detect when the user closes it?



I am using jquery within the project so a jquery solution would be good. Cheers!


More From » jquery

 Answers
18

If you have control over the contents of the pop-up, handle the window's unload event there and notify the original window via the opener property, checking first whether the opener has been closed. Note this won't always work in Opera.



window.onunload = function() {
var win = window.opener;
if (!win.closed) {
win.someFunctionToCallWhenPopUpCloses();
}
};


Since the unload event will fire whenever the user navigates away from the page in the pop-up and not just when the window is closed, you should check that the pop-up has actually closed in someFunctionToCallWhenPopUpCloses:



var popUp = window.open(popup.html, thePopUp, );
function someFunctionToCallWhenPopUpCloses() {
window.setTimeout(function() {
if (popUp.closed) {
alert(Pop-up definitely closed);
}
}, 1);
}


If you don't have control over the contents of the pop-up, or if one of your target browsers does not support the unload event, you're reduced to some kind of polling solution in the main window. Adjust interval to suit.



var win = window.open(popup.html, thePopUp, );
var pollTimer = window.setInterval(function() {
if (win.closed !== false) { // !== is required for compatibility with Opera
window.clearInterval(pollTimer);
someFunctionToCallWhenPopUpCloses();
}
}, 200);

[#96167] Saturday, July 17, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
monetm

Total Points: 615
Total Questions: 103
Total Answers: 119

Location: Finland
Member since Fri, Oct 21, 2022
2 Years ago
;