为什么window.open(...)。onunload = function(){...}无法正常工作? [英] 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>
我希望这会提醒hola!在使用 window.open
打开的窗口关闭后的原始窗口中。相反,它警告hola!在使用 window.open
打开新窗口后立即在原始窗口中。它为什么这样工作?有没有办法做我想做的事情?
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?
推荐答案
窗口首先加载一个空白页然后卸载页面,导致卸载
事件。
然后您的页面加载。在 onload
事件触发时尝试附加事件以避免这种情况。
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.
document.getElementById('openWindow').onclick = function () {
var windowref = window.open('tests2.html');
windowref.onload = function() {
windowref.onunload = function () {
window.alert('hola!');
};
}
};
这篇关于为什么window.open(...)。onunload = function(){...}无法正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!