When doing some questions about online membership, we often need to determine whether the user is offline based on whether the browser is closed, and then remove the user from the session and application.
Because the browser is stateless, there are two situations when the capture browser is closed:
1. actually close the browser (a. Click the close button B. Right-click the taskbar to close c. press alt + F4 to close)
2. Refresh the browser.
How can we identify and distinguish these two actions?
I. Javascript code processing method: Copy codeThe Code is as follows: function window. onbeforeunload ()
{
// Click the close button in the upper-right corner of the browser or press alt + F4 to close it.
If (event. clientX> document. body. clientWidth & event. clientY <0 | event. altKey)
{
// Alert ("click the close button ");
Document. getElementById ("hiddenForm: hiddenBtn"). click ();
// Window. event. returnValue = "are you sure you want to exit this page? ";
}
// Right-click the task bar and choose Close. S or press alt + F4 to disable
Else if (event. clientY> document. body. clientHeight | event. altKey)
{
// Alert ("right-click to close the taskbar ");
Document. getElementById ("hiddenForm: hiddenBtn"). click ();
// Window. event. returnValue = "are you sure you want to exit this page? ";
}
// Refresh in other cases
Else
{
// Alert ("Refresh page ");
}
}
Where event. clientX cursor X coordinates
Document. body. clientWidth form workspace width
Event. clientY mouse cursor Y coordinate
Event. altKey: whether to press alt
Ii. Event capturing methods: Copy codeThe Code is as follows: <body scroll = "no" onbeforeunload = "return CloseEvent ();" onunload = "UnLoadEvent ()">
</Body>
<Script language = "JavaScript" type = "text/javascript">
Var DispClose = true;
Function CloseEvent ()
{
If (DispClose)
{
Return "do you want to leave the current page? ";
}
}
Function UnLoadEvent ()
{
DispClose = false;
// Process the action before closing the page here
}
</Script>
An onbeforeunload event is triggered before the page is detached. If you select Yes, The unload event is triggered. Otherwise, no operation is performed on the returned page.