Javascript判断页面刷新或关闭的方法(转)
Onunload,onbeforeunload都是在刷新或关闭时调用,可以在<script>脚本中通过window.onunload来指定或者在<body>里指定。区别在于onbeforeunload在onunload之前执行,它还可以阻止onunload的执行。
Onbeforeunload也是在页面刷新或关闭时调用,Onbeforeunload是正要去服务器读取新的页面时调用,此时还没开始读取;而onunload则已经从服务器上读到了需要加载的新的页面,在即将替换掉当前页面时调用。Onunload是无法阻止页面的更新和关闭的。而 Onbeforeunload 可以做到。 页面加载时只执行onload 1、onbeforeunload事件: 1 ·object.onbeforeunload = handler 2 ·<element onbeforeunload = “handler” … ></element>
触发于: 1 <html xmlns="http://www.w3.org/1999/xhtml"> 2 <head> 3 <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> 4 <title>onbeforeunload测试</title> 5 <script> 6 function checkLeave(){ 7 event.returnValue="确定离开当前页面吗?"; 8 } 9 </script> 10 </head> 11 <body onbeforeunload="checkLeave()"> 12 </body> 13 </html>
2、onunload事件 1 ·object.onbeforeunload = handler 2 ·<element onbeforeunload = "handler"></element>
描述: 触发于: 1 <html xmlns="http://www.w3.org/1999/xhtml"> 2 <head> 3 <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> 4 <title>onunload测试</title> 5 <script> 6 function checkLeave(){ 7 alert("欢迎下次再来!"); 8 } 9 </script> 10 </head> 11 <body onunload="checkLeave()"> 12 </body> 13 </html>
一个判断页面是否真的关闭和刷新的好方法: 1 window.onbeforeunload=function (){ 2 alert("===onbeforeunload==="); 3 if(event.clientX>document.body.clientWidth && event.clientY < 0 || event.altKey){ 4 alert("你关闭了浏览器"); 5 }else{ 6 alert("你正在刷新页面"); 7 } 8 }
这段代码就是判断触发onbeforeunload事件时,鼠标是否点击了关闭按钮,或者按了ALT+F4来关闭网页,如果是,则认为系统是关闭网页,否则在认为系统是刷新网页。 |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述