如何捕捉事件并区分关闭和刷新事件

how to catch the event and distinguish close and refresh event

本文关键字:事件 刷新 何捕捉      更新时间:2023-09-26

在我的项目中,我需要在浏览器中使用关闭事件,通过web,服务器和数据库处理用户退出时的信息。我不知道如何捕捉事件和区分关闭和刷新事件。

我试了这些代码:

window.onbeforeunload = function() {      
    var n = window.event.screenX - window.screenLeft;      
    var b = n > document.documentElement.scrollWidth-20;      
    if(b && window.event.clientY < 0 || window.event.altKey) {      
        alert("close event");      
    }else{     
        alert("refresh event");      
    }  
} 

但是它只捕获刷新事件。有没有更好的办法来解决这个问题?

此外,我已经阅读了如何区分浏览器关闭和刷新事件在Chrome?

一个想法:通过cookie来判断是否登录。

而且浏览器通常不会禁用cookie。

如果cookie是禁用的,您可以要求用户启用它。

下面是一个cookie的例子:

function setCookie(name, value) //cookies setting 
{ 
var argv = setCookie.arguments; 
var argc = setCookie.arguments.length; 
var expires = (argc > 2) ? argv[2] : null; 
if(expires!=null) 
{ 
var LargeExpDate = new Date (); 
LargeExpDate.setTime(LargeExpDate.getTime() + (expires*1000*3600*24)); 
} 
document.cookie = name +value   } 
//In Js
setCookie("a","34234523542");   
//read cookie: 
function WM_readCookie(name) 
{ 
//if there is no cookie,return false;or get value and return value
if(document.cookie == '') 
return false; 
else 
return 
unescape(WM_getCookieValue(name)); 
} 

function WM_getCookieValue(name) 
{ 
// Declare variables. 
var firstChar,lastChar; 
// Get the entire cookie string. 
// (This may have other 
name=value pairs in it.) 
var theBigCookie = document.cookie; 
// Grab 
just this cookie from theBigCookie string. 
// Find the start of 
'name'. 
firstChar = theBigCookie.indexOf(name); 
// If you found it, 

if(firstChar != -1) 
{ 
// skip 'name' and '='. 
firstChar += 
name.length + 1; 
// Find the end of the value string (i.e. the next 
';'). 
lastChar = theBigCookie.indexOf(';', firstChar); 

if(lastChar == -1) lastChar = theBigCookie.length; 
// Return the 
value. 
return theBigCookie.substring(firstChar, lastChar); 
} else 
{ 
// If there was no cookie, return false. 
return false; 
} 
}