JavaScript中onbeforeunload与onunload事件的区别及应用

作者:小圆点时间:2026-10-26 19:09:26浏览:436

本文详细解析JavaScript中onbeforeunload与onunload事件在页面刷新或关闭时的执行顺序与区别。onbeforeunload可在onunload前执行并阻止页面离开,而onunload无法阻止。文章提供了两种事件的用法、触发场景及浏览器兼容性说明,并给出通过event.clientX等属性判断用户是关闭浏览器还是刷新页面的具体代码示例。

onbeforeunload与onunload事件概述

onunload和onbeforeunload事件均在页面刷新或关闭时触发,可以通过在<script>标签内使用window.onunload指定,或在<body>标签中直接指定。两者的主要区别在于执行顺序:onbeforeunload在onunload之前执行,且onbeforeunload具备阻止onunload执行的能力。


onbeforeunload在页面即将向服务器请求新页面时触发,此时尚未开始读取;而onunload则在服务器已返回新页面内容、即将替换当前页面时触发。onunload无法阻止页面的导航或关闭操作,但onbeforeunload可以。



在页面正常加载过程中,仅会执行onload事件。


当用户关闭页面时,执行顺序为先触发onbeforeunload,最后触发onunload。


当用户刷新页面时,执行顺序依次为:先触发onbeforeunload,接着触发onunload,最后触发新页面的onload。



1、onbeforeunload事件:

onbeforeunload事件详解

目前Firefox和IE浏览器均支持onbeforeunload事件,而Opera浏览器尚未提供支持。


具体用法如下:


object.onbeforeunload = handler


<element onbeforeunload = "handler" ... ></element>


事件描述:


触发该事件时会弹出一个包含“确定”和“取消”按钮的对话框。若用户点击“确定”,则离开当前页面;若点击“取消”,则停留在当前页面。handler函数可以返回一个字符串,该字符串将作为对话框显示的提示文本。



该事件在以下场景中触发:


关闭浏览器窗口时。


通过地址栏或收藏夹导航至其他页面时。


点击“返回”、“前进”、“刷新”或“主页”按钮时。


点击指向其他页面的URL链接时。


调用以下任一方法时:click,document write,document open,document close,window close,window navigate,window NavigateAndFind,location replace,location reload,form submit。


使用window open打开新页面,并将当前窗口的名称传递给新页面时。


重新赋值location.href时。


通过input type="submit"按钮提交具有指定action属性的表单时。


该事件可应用于以下HTML元素:


BODY, FRAMESET, window


平台支持情况:


IE4+/Win, Mozilla 1.7a+, Netscape 7.2+, Firefox0.9+


示例代码:


代码如下:

 
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>onbeforeunload测试</title>
<script>
function checkLeave(){
event.returnValue="确定离开当前页面吗?";
   } 
</script>
</head>
<body onbeforeunload="checkLeave()">
</body>
</html>

2、onunload事件

onunload事件详解

onunload事件用法:


object.onbeforeunload = handler


<element onbeforeunload = "handler"></element>



事件描述:


当用户关闭页面时触发onunload事件。



触发场景:


关闭浏览器窗口时。


通过地址栏或收藏夹导航至其他页面时。


点击“返回”、“前进”、“刷新”或“主页”按钮时。


点击指向其他页面的URL链接时。


调用以下任一方法时:click,document write,document open,document close,window close,window navigate,window NavigateAndFind,location replace,location reload,form submit。


使用window open打开新页面,并将当前窗口的名称传递给新页面时。


重新赋值location.href时。


通过input type="submit"按钮提交具有指定action属性的表单时。


示例代码:


代码如下:

 
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>onunload测试</title>
<script>
function checkLeave(){
alert("欢迎下次再来!");
   } 
</script>
</head>
<body onunload="checkLeave()">
</body>
</html>

判断页面关闭与刷新的代码示例

一种判断页面是真正关闭还是刷新的方法:


代码如下:

 
window.onbeforeunload=function (){
alert("===onbeforeunload===");
if(event.clientX>document.body.clientWidth && event.clientY < 0 || event.altKey){
alert("你关闭了浏览器");
}else{
alert("你正在刷新页面");
} 
} 

这段代码通过判断触发onbeforeunload事件时,鼠标是否点击了关闭按钮,或者是否按下了ALT+F4组合键来关闭网页。如果满足条件,则判定为关闭网页;否则,判定为刷新页面。

作者最新文章