利用onbeforeunload与onunload区分页面关闭与刷新

作者:异步漫步时间:2026-10-29 09:33:45浏览:79

HTML body标签仅支持onload、onunload和onbeforeunload事件,缺乏直接的onclose事件。由于刷新和关闭都会触发onunload,可通过在onbeforeunload中设置标记变量,并在onunload中读取该变量来区分用户是执行了页面刷新还是真正关闭了浏览器窗口。

区分页面关闭与刷新的原理

HTML的body标签仅包含onload、onunload和onbeforeunload事件,并不提供onclose事件。无论是执行页面刷新还是关闭浏览器窗口,onunload事件均会被触发。因此,需要特定的逻辑来捕捉真正的页面关闭行为。



当页面正常加载时,系统仅执行onload事件。



当用户关闭页面时,系统仅执行onunload事件。



若执行页面刷新,事件触发顺序依次为onbeforeunload、onunload,最后执行onload。利用这一机制,可以在onbeforeunload事件中设置一个标记变量,随后在onunload事件中检查该标记的状态,从而准确判断页面是处于刷新状态还是关闭状态。



代码实现示例

<html>


<head>


<title>判断页面是关闭还是刷新</title>


</head>



<body onunload="fclose();" onload="fload();" onbeforeunload="bfunload();">


<script language="javascript">


var s = "test";


function fclose()


  {

if(s=="no")


alert('unload me!='+s+'这是刷新页面!');


else


alert('这是关闭页面');


  }

function fload()


  {

alert("load me!="+s);


  }

function bfunload()


  {

s = "no";


  }

</script>


</body>


</html>

作者最新文章