在窗口关闭或页面刷新时运行 JavaScript 代码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13443503/
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
Run JavaScript code on window close or page refresh?
提问by Peter
Is there a way to run a final JavaScript code when a user closes a browser window or refreshes the page?
当用户关闭浏览器窗口或刷新页面时,有没有办法运行最终的 JavaScript 代码?
I'm thinking of something similar to onload but more like onclose? Thanks.
我在想类似于 onload 但更像 onclose 的东西?谢谢。
I don't like the onbeforeunload method, which always yields to a confirmation box popping up (leave page/ stay on mozilla) or (reload/ don't reload on chrome). Is there a way to execute the code quietly?
我不喜欢 onbeforeunload 方法,它总是会弹出一个确认框(离开页面/留在 mozilla 上)或(重新加载/不要在 chrome 上重新加载)。有没有办法安静地执行代码?
采纳答案by Peter
Ok, I found a working solution for this, it consists of using the beforeunloadevent and then making the handler return null. This executes the wanted code without a confirmation box popping-up. It goes something like this:
好的,我为此找到了一个可行的解决方案,它包括使用beforeunload事件然后使处理程序返回null。这将执行所需的代码,而不会弹出确认框。它是这样的:
window.onbeforeunload = closingCode;
function closingCode(){
// do something...
return null;
}
Hope this helps.
希望这可以帮助。
回答by JCOC611
There is both window.onbeforeunloadand window.onunload, which are used differently depending on the browser. You can assing them either by setting the window properties to functions, or using the .addEventListener:
有window.onbeforeunload和window.onunload,根据浏览器的不同使用方式不同。您可以通过将窗口属性设置为函数或使用.addEventListener:
window.onbeforeunload = function(){
// Do something
}
// OR
window.addEventListener("beforeunload", function(e){
// Do something
}, false);
Usually, onbeforeunloadis used if you need to stop the user from leaving the page (ex. the user is working on some unsaved data, so he/she should save before leaving). onunloadisn't supported by Opera, as far as I know, but you could always set both.
通常,onbeforeunload用于阻止用户离开页面(例如,用户正在处理一些未保存的数据,因此他/她应该在离开前保存)。Operaonunload不支持,据我所知,但你总是可以同时设置。
回答by Paras
jQuery version:
jQuery 版本:
$(window).unload(function(){
// Do Something
});
Update: jQuery 3:
更新:jQuery 3:
$(window).on("unload", function(e) {
// Do Something
});
Thanks Garrett
谢谢加勒特
回答by Mike
Sometimes you may want to let the server know that the user is leaving the page. This is useful, for example, to clean up unsaved images stored temporarily on the server, to mark that user as "offline", or to log when they are done their session.
有时您可能想让服务器知道用户正在离开页面。这很有用,例如,清理临时存储在服务器上的未保存图像、将该用户标记为“离线”或在他们完成会话后进行记录。
Historically, you would send an AJAX request in the beforeunloadfunction, however this has two problems. If you send an asynchronous request, there is no guarantee that the request would be executed correctly. If you send a synchronous request, it is more reliable, but the browser would hang until the request has finished. If this is a slow request, this would be a huge inconvenience to the user.
过去,您会在beforeunload函数中发送 AJAX 请求,但这有两个问题。如果您发送异步请求,则不能保证该请求会被正确执行。如果你发送同步请求,它更可靠,但浏览器会挂起,直到请求完成。如果这是一个缓慢的请求,这将给用户带来巨大的不便。
Luckily, we now have navigator.sendBeacon(). By using the sendBeacon()method, the data is transmitted asynchronously to the web server when the User Agent has an opportunity to do so, without delaying the unload or affecting the performance of the next navigation. This solves all of the problems with submission of analytics data: the data is sent reliably, it's sent asynchronously, and it doesn't impact the loading of the next page. Here is an example of its usage:
幸运的是,我们现在有navigator.sendBeacon(). 通过使用该sendBeacon()方法,当用户代理有机会这样做时,将数据异步传输到Web服务器,而不会延迟卸载或影响下一次导航的性能。这解决了提交分析数据的所有问题:数据发送可靠,异步发送,不影响下一页的加载。下面是它的用法示例:
window.addEventListener("unload", logData, false);
function logData() {
navigator.sendBeacon("/log.php", analyticsData);
}
sendBeacon()is supportedin:
sendBeacon()被支持在:
- Edge 14
- Firefox 31
- Chrome 39
- Safari 11.1
- Opera 26
- iOS Safari 11.4
- 边缘 14
- 火狐 31
- 铬 39
- Safari 11.1
- 歌剧26
- iOS Safari 11.4
It is NOT currently supported in:
目前不支持:
- Internet Explorer
- Opera Mini
- IE浏览器
- 歌剧迷你
Here is a polyfill for sendBeacon()in case you need to add support for unsupported browsers. If the method is not available in the browser, it will send a synchronous AJAX request instead.
这是sendBeacon() 的 polyfill,以防您需要添加对不受支持的浏览器的支持。如果该方法在浏览器中不可用,它将改为发送同步 AJAX 请求。
回答by Gurpreet Singh
You can use window.onbeforeunload.
您可以使用window.onbeforeunload.
window.onbeforeunload = confirmExit;
function confirmExit(){
alert("confirm exit is being called");
return false;
}
回答by davejoem
The documentation here encourages listening to the onbeforeunload event and/or adding an event listener on window.
此处的文档鼓励侦听 onbeforeunload 事件和/或在窗口上添加事件侦听器。
window.addEventListener('beforeunload', function(event) {
//do something here
}, false);
You can also just populate the .onunload or .onbeforeunload properties of window with a function or a function reference.
您也可以使用函数或函数引用填充 window 的 .onunload 或 .onbeforeunload 属性。
Though behaviour is not standardized across browsers, the function may return a value that the browser will display when confirming whether to leave the page.
尽管跨浏览器的行为没有标准化,但该函数可能会返回一个值,浏览器在确认是否离开页面时将显示该值。
回答by Phssthpok
The event is called beforeunload, so you can assign a function to window.onbeforeunload.
该事件被调用beforeunload,因此您可以为 分配一个函数window.onbeforeunload。
回答by Dane Balia
You can try something like this:
你可以尝试这样的事情:
<SCRIPT language="JavaScript">
<!--
function loadOut()
{
window.location="http://www.google.com";
}
//-->
</SCRIPT>
<body onBeforeUnload="loadOut()">

