为什么 window.open(...).onunload = function () { ... } 不能按我的预期工作?
我希望能够知道我打开的窗口何时被用户关闭。这是我尝试监控此问题的代码:
<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 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
窗口首先加载一个空白页面,然后卸载该页面,从而引发
unload
事件。然后加载您的页面。尝试在
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.Simple demo
尝试在窗口加载后添加
JSBin 示例
Try adding after the window loads
JSBin Example
Digital Plane 答案似乎有效,但感觉有点脆弱(例如,如果浏览器改变行为并停止加载/卸载“about:blank”,则事件将停止触发。)
我的解决方案是检查
windowref.location.href弹出窗口的
并在“about:blank”时跳过处理程序:Digital Plane answer seems to work, but it feels a bit brittle (e.g. if the browser changed behavior and stopped loading/unloading "about:blank" the event would stop firing.)
My solution was to check
windowref.location.href
of the popup and skip the handler when it is "about:blank":对此的回复很晚,但我刚刚在 aspx 页面中使用此代码遇到了同样的问题:
我的错误是省略给按钮
type="button"
,因此页面默认到type="submit"
并在单击按钮时发回(我假设在页面重新加载时删除对事件侦听器的引用)。为按钮提供一种按钮解决了该问题:Very late response to this one, but I've just had the same issue with this code in an aspx page:
My mistake was to omit giving the button a
type="button"
, so the page defaults totype="submit"
and posts back when the button is clicked (I assume removing the reference to the event listener when the page reloads). Giving the button a type of button fixed the issue: