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!
Here is the code: var win = window. open('http://www.google.com', 'google','width=800,height=600,status=0,toolbar=0'); var timer = setInterval(function() { if(win. closed) { clearInterval(timer); alert('closed'); } }, 1000);
In Javascript, popup boxes are used to display the message or notification to the user. There are three types of pop-up boxes in JavaScript namely Alert Box, Confirm Box and Prompt Box. Alert Box: It is used when a warning message is needed to be produced.
You can use JavaScript to create popup windows. Popup windows are different to simply opening a new browser window. If you only want to open a new browser window you can add the target="_blank" attribute within the <a> element (see this article on opening a new window in HTML).
self. close(); should do it. That should work from within the popup.
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);
There is a very simple solution to your problem.
First make a new object which will open up a pop like this :
var winObj = window.open('http://www.google.com','google','width=800,height=600,status=0,toolbar=0');
In order to know when this popup window is closed, you just have to keep checking this with a loop like the following :
var loop = setInterval(function() { if(winObj.closed) { clearInterval(loop); alert('closed'); } }, 1000);
Now you can replace alert with any javascript code you want.
Have Fun! :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With