試試這個:
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