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

时间:2016-06-30 13:20:41

标签: javascript events

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

我尝试了这些代码:

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");      
    }  
} 

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

此外,我已阅读How to differentiate browser close and refresh events in Chrome?,但它没有给我答案。

1 个答案:

答案 0 :(得分:0)

一个想法:通过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; 

} 
} 
相关问题