试试这个:
var win = window.open(url, name);
win.onunload = afterChildClose; // afterChildClose() is the function.
win.close(); // afterChildClose() should fire now.
所有这些代码将设在父窗口的JavaScript执行(包括afterChildClose())。您正在创建窗口并将该功能分配给卸载事件。
哦,我刚想到的一件事。如果子窗口刷新或导航到另一个URL,则onunload事件也会触发。如果您只想在窗口关闭时触发事件,则应在win.closed中的afterChildClose()中包含一个检查。
编辑:这里是代码,我放在一起尝试这两个示例页面。
父窗口:
<html>
<body>
<script type="text/javascript">
var win = window.open("secondwindow.html", "woo");
win.onunload =onun;
function onun() {
if(win.location != "about:blank") // This is so that the function
// doesn't do anything when the
// window is first opened.
{
alert("closed");
}
}
</script>
</body>
</html>
子窗口( “secondwindow.html”):
<html>
<body>
<script type="text/javascript">
setTimeout('window.close();', 5000);
</script>
</body>
</html>
当我尝试打开Firefox中的第一个文件,它打开的窗口,窗口等待5秒和退出,并且第一个文档显示alert(),所以即使在子窗口关闭时它仍在工作。
为了回应您对我的回答的最新评论,我恐怕无法想到在窗口关闭时不会调用该函数的原因。你可以在你打开窗口的地方发布你的代码,以及你在关闭时试图调用的函数吗?我可能能够帮助你,但现在我没有想法。 – Sean 2009-07-11 23:31:49