【发布时间】:2011-08-08 09:43:22
【问题描述】:
我正在以这种方式打开 Facebook 共享的子窗口:
window.open(sharingUrl,'','toolbar=0,status=0,width=626,height=436');
当用户点击分享或关闭时,窗口会自动关闭...
有没有办法为这些事件添加监听器?
【问题讨论】:
标签: javascript dom-events cross-domain
我正在以这种方式打开 Facebook 共享的子窗口:
window.open(sharingUrl,'','toolbar=0,status=0,width=626,height=436');
当用户点击分享或关闭时,窗口会自动关闭...
有没有办法为这些事件添加监听器?
【问题讨论】:
标签: javascript dom-events cross-domain
为了将来的参考,我想分享另一个不需要setInterval 的解决方案:
var child = window.open('http://google.com','','toolbar=0,status=0,width=626,height=436');
child.onunload = function(){ console.log('Child window closed'); };
【讨论】:
这样就可以了
<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>
【讨论】:
如果在调用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);
}
}
其他人注意:如果您曾经处于可以控制子窗口中的 html 的情况,您可以利用 onbeforeunload 事件并提醒父窗口。
【讨论】:
onbeforeunload。
setInterval 调用了一个直到之后才定义的函数,为什么这会起作用?