在窗口关闭或页面刷新时运行 JavaScript 代码? [英] Run JavaScript code on window close or page refresh?
问题描述
有没有办法在用户关闭浏览器窗口或刷新页面时运行最终的 JavaScript 代码?
Is there a way to run a final JavaScript code when a user closes a browser window or refreshes the page?
我在考虑类似于 onload 但更像 onclose 的东西?谢谢.
I'm thinking of something similar to onload but more like onclose? Thanks.
我不喜欢 onbeforeunload 方法,它总是会弹出一个确认框(离开页面/留在 mozilla 上)或(重新加载/不要在 chrome 上重新加载).有没有办法安静地执行代码?
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?
推荐答案
好的,我找到了一个可行的解决方案,它包括使用 beforeunload
事件,然后让处理程序返回 空
.这将执行所需的代码,而不会弹出确认框.它是这样的:
Ok, I found a working solution for this, it consists of using the beforeunload
event and then making the handler return null
. This executes the wanted code without a confirmation box popping-up. It goes something like this:
window.onbeforeunload = closingCode;
function closingCode(){
// do something...
return null;
}
这篇关于在窗口关闭或页面刷新时运行 JavaScript 代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!