1

In my project I need to use close event in browser through web, server and database deal with the information when user log out. I do not know how to catch the event and distinguish close and refresh event.

I tried these code:

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

But it only catches the refresh event. Is there a better way to solve the problem?

Besides,I have read the How to differentiate browser close and refresh events in Chrome?,but it doesn't give me the answer.

Community
  • 1
  • 1
  • I'm trying to understand you code. So when the mouse is outside of the window or the alt key is pressed, it's a close event? – 4castle Jun 30 '16 at 13:33
  • I may be wrong, but I would expect that you can't tell the difference between a refresh and a leave. As far as that page is concerned you're leaving either way, whether are going to return is almost certainly unknown to the page at the time of leaving. – DBS Jun 30 '16 at 13:35

1 Answers1

0

An idea: Judge by cookie to get the information if it is log in.

And the browser usually doesn't disable cookies.

If the cookie is disable, you may ask user to enable it.

Here is an example for 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; 

} 
} 
alan_stack
  • 52
  • 5