[英]Why does window.open(…).onunload = function () { … } not work as I expect?
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.在使用window.open
打开的窗口关闭后的原始窗口中。 Instead, it alerts "hola!"相反,它会提醒“你好!” in the original window immediately after opening the new window with window.open
.在使用window.open
打开新窗口后立即在原始窗口中。 Why does it work like this?为什么它会这样工作? Is there a way of doing what I want to do?有没有办法做我想做的事?
The window first loads with a blank page and then unloads the page, causing the unload
event.窗口首先加载一个空白页面,然后卸载页面,导致unload
事件。
Your page then loads.然后您的页面加载。 Try attaching the event when the onload
event fires to avoid this.尝试在onload
事件触发时附加该事件以避免这种情况。
document.getElementById('openWindow').onclick = function () {
var windowref = window.open('tests2.html');
windowref.onload = function() {
windowref.onunload = function () {
window.alert('hola!');
};
}
};
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!');
};
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.