JavaScript判断网页关闭与刷新的几种实现方案

作者:拾光

时间:2026-10-29

浏览:503

本文详解如何利用JavaScript的onunload和onbeforeunload事件区分用户是刷新、跳转还是关闭网页。通过检测窗口坐标、屏幕位置及时间戳标记,提供兼容IE、Firefox及多标签页浏览器的完整代码示例,解决传统方法在特定场景下的失效问题。

文章目录

判断原理与事件机制

核心原理在于利用页面离开时的onunload事件,通过检测当前浏览器窗口的大小及位置信息,从而推断用户执行的是刷新、跳转还是关闭操作。

基础实现代码

具体实现代码见下方示例。


window.onunload = function(){    
    var a_n = window.event.screenX - window.screenLeft;    
    var a_b = a_n > document.documentElement.scrollWidth-20;    
    if(a_b && window.event.clientY< 0 || window.event.altKey){    
         alert('关闭页面行为'); 
    }else{ 
         alert('跳转或者刷新页面行为');   
      } 
}

该方法在使用浏览器右上角关闭按钮时有效,但在处理选项卡关闭或任务栏关闭行为时,此方法无法准确识别。

JavaScript中仅存在onload、onunload和onbeforeunload事件,并不提供专门的onclose事件。

无论是页面刷新还是关闭,onunload事件均会被触发,因此仅靠该事件无法直接区分两者。

要准确捕捉页面关闭行为,需结合多个事件的生命周期:页面加载时仅触发onload;页面关闭时仅触发onunload;而页面刷新则会依次触发onbeforeunload、onunload,最后再次触发onload。

基于上述机制,可在onbeforeunload事件中设置一个标记变量,随后在onunload事件中检查该标记,以此判断页面是否真正被关闭。以下是更完整且兼容Firefox的实现方案。

相关代码示例如下。


<mce:script type="text/javascript"><!--
    function close(evt) //author: sunlei
    {  
      var isIE=document.all?true:false;
      evt = evt ? evt :(window.event ? window.event : null);
      if(isIE){//IE浏览器
        var n = evt.screenX - window.screenLeft;
        var b = n > document.documentElement.scrollWidth-20;
        if(b && evt.clientY<0 || evt.altKey){
          //alert("是关闭而非刷新");
          window.location.href="../include/logout.php";
        }
        else{
          //alert("是刷新而非关闭");
          return false;
        }
      }
      else{//火狐浏览器
        if(document.documentElement.scrollWidth!=0)
        {
          //alert("是刷新而非关闭");
          //window.location.href="report_list.php?ss=1";
          return false;
          
        }
        else{
          alert("是关闭而非刷新");
          //window.location.href="repost_list.php?ss=0";
          //alert("bbbbbbb");
        }
      }
    }
// --></mce:script>
<BODY onunload="close(event);"> 

多标签页兼容方案

前述方法无法适用于支持多标签页的浏览器(如360浏览器、IE8等),因此需要引入另一种检测方式。

新的代码实现如下。


function CloseOpen(event) { 
     if(event.clientX<=0 || event.clientY<0) { 
       //获取当前时间
      var date=new Date();
      //将date设置为过去的时间
      alert("关闭网页");
      date.setTime(date.getTime()-10000);
      //将userId这个cookie删除
      document.cookie="zhuangtao;expire="+date.toUTCString();
      document.cookie="quanxianzifucuan;expire="+date.toUTCString();
      document.cookie="quanxian;expire="+date.toUTCString();
     s0 += "关闭窗口!"; sw = 1;
      onbeforeunload();
      // window.event.returnValue = '关闭浏览器将退出系统.';
     } 
     else 
     { 
        alert("刷新或离开"); 
     } 
 } 
       
        var currentKeyCode = -1;

  function document.onkeydown() { // 本窗口的所有下属页面都必须含有本函数

    top.currentKeyCode = event.keyCode;
  }

  function onbeforeunload(){
  
   var sw = 0, s0 = "";
    if (currentKeyCode == 116) 
    {
      s0 += "刷新窗口!(F5)";
    }
    else 
    {
      if ((event.altKey)&&(currentKeyCode == 115)) 
      {
         s0 += "关闭窗口!(alt+F4)"; sw = 1;
          //获取当前时间
          var date=new Date();
          //将date设置为过去的时间
         alert("关闭窗口");
          date.setTime(date.getTime()-10000);
          //将userId这个cookie删除
          document.cookie="zhuangtao;expire="+date.toUTCString();
          document.cookie="quanxianzifucuan;expire="+date.toUTCString();
          document.cookie="quanxian;expire="+date.toUTCString();
      }
      else 
      {
        if ((event.clientX > 0)&&(event.clientX < document.body.clientWidth)) 
        {
         s0 += "刷新窗口!";
        }
        else 
        {
        //获取当前时间
          var date=new Date();
          //将date设置为过去的时间
          alert("关闭网页");
          date.setTime(date.getTime()-10000);
          //将userId这个cookie删除
          document.cookie="zhuangtao;expire="+date.toUTCString();
          document.cookie="quanxianzifucuan;expire="+date.toUTCString();
          document.cookie="quanxian;expire="+date.toUTCString();
         s0 += "关闭窗口!"; sw = 1;
        }
      }
    }
    if (sw == 1) 
    {
     event.returnValue = "";
    }
    else 
    {
     currentKeyCode = -1;
    }
  
  }

<body onunload="CloseOpen(event)" ></body></html>

尽管上述方法在通过任务栏关闭窗口时仍可能受限,但基本能够满足大多数场景下的判断需求。

以上即为JavaScript判断网页关闭与刷新行为的详细介绍,希望读者能从中受益。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章