Javascript 为什么 window.open(...).onunload = function () { ... } 不像我预期的那样工作?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7476660/
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
Why does window.open(...).onunload = function () { ... } not work as I expect?
提问by Steven Oxley
I want to be able to tell when a window that I open is closed by the user. This is the code of my attempt at monitoring this:
我希望能够知道用户何时关闭了我打开的窗口。这是我尝试监控的代码:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
window.document.onready = function () {
document.getElementById('openWindow').onclick = function () {
var windowref = window.open('tests2.html');
windowref.onunload = function () {
window.alert('hola!');
};
};
};
</script>
</head>
<body>
<button id='openWindow'>Open Window</button>
</body>
</html>
I would expect this to alert "hola!" in the original window after the window that was opened with window.open
was closed. Instead, it alerts "hola!" in the original window immediately after opening the new window with window.open
. Why does it work like this? Is there a way of doing what I want to do?
我希望这会提醒“你好!” 在打开的窗口window.open
关闭后的原始窗口中。相反,它会提醒“你好!” 在用 打开新窗口后立即在原始窗口中window.open
。为什么它会这样工作?有没有办法做我想做的事?
回答by Digital Plane
The window first loads with a blank page and then unloads the page, causing the unload
event.
Your page then loads. Try attaching the event when the onload
event fires to avoid this.
该窗口首先加载一个空白页面,然后卸载该页面,从而引发该unload
事件。
然后您的页面加载。尝试在onload
事件触发时附加事件以避免这种情况。
document.getElementById('openWindow').onclick = function () {
var windowref = window.open('tests2.html');
windowref.onload = function() {
windowref.onunload = function () {
window.alert('hola!');
};
}
};
回答by epascarello
Try adding after the window loads
在窗口加载后尝试添加
document.getElementById('openWindow').onclick = function () {
var windowref = window.open('tests2.html');
windowref.window.onload = function(){ //wait til load to add onunload event
windowref.window.onunload = function () {
window.alert('hola!');
};
}
};