Javascript JS:在子窗口关闭时收听
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5712195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JS: Listen when child window is closed
提问by Oleg Tarasenko
I am opening child window for facebook sharing this way:
我正在以这种方式为 facebook 共享打开子窗口:
window.open(sharingUrl,'','toolbar=0,status=0,width=626,height=436');
The window is automatically closed when user click share or close... Is there a way to add a listeners to these events?
当用户单击共享或关闭时,窗口会自动关闭...有没有办法为这些事件添加侦听器?
回答by jessegavin
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.
如果在调用时存储对子窗口的引用window.open()
,则可以setInterval()
使用该window.closed
属性轮询以查看窗口是否仍处于打开状态。下面的示例每秒检查两次。
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 onbeforeunloadevent and alert the parent window.
对其他人的注意:如果您曾经处于可以控制子窗口中的 html 的情况,您可以利用onbeforeunload事件并提醒父窗口。
回答by Odubuc
For future references, I'd like to share another solution that doesn't require setInterval
:
为了将来参考,我想分享另一个不需要的解决方案setInterval
:
var child = window.open('http://google.com','','toolbar=0,status=0,width=626,height=436');
child.onunload = function(){ console.log('Child window closed'); };
回答by Maddy
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>