How to listen for child window closing?
JavascriptDom EventsCross DomainJavascript Problem Overview
I am opening a child window for Facebook sharing this way:
window.open(sharingUrl,'','toolbar=0,status=0,width=626,height=436');
The window is automatically closed when a user clicks share or close...
Is there a way to add a listener to these events?
Javascript Solutions
Solution 1 - Javascript
If you store a reference to the child window when you call window.open()
, then you can poll using setInterval()
to see whether the window is still open using the window.closed
property. The example below checks twice per second.
var child = window.open('http://google.com','','toolbar=0,status=0,width=626,height=436');
var timer = setInterval(checkChild, 500);
function checkChild() {
if (child.closed) {
alert("Child window closed");
clearInterval(timer);
}
}
Note to others: If you are ever in a situation where you have control over the html in the child window, you could make use of the onbeforeunload event and alert the parent window.
Solution 2 - Javascript
For future references, I'd like to share another solution that doesn't require setInterval
:
var child = window.open('http://google.com','','toolbar=0,status=0,width=626,height=436');
child.onunload = function(){ console.log('Child window closed'); };
Solution 3 - Javascript
This will work fine
<html>
<head>
<title>Detecting browser close in IE</title>
<script type="text/javascript">
window.onbeforeunload = function(){ myUnloadEvent(); }
function myUnloadEvent() {
alert ('You can have Ur Logic Here ,');
}
</script>
</head>
</script>
</head>
<body >
<h1>Close the Window now</h1>
</body>
</html>