How to capture closed browsers and refresh events _ javascript tips-js tutorial

Source: Internet
Author: User
When we do 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, next, I will share with you the specific capturing methods. When you have questions about online membership, we often need to determine whether the user is offline based on whether the browser is closed, 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:

The 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:

The Code is as follows:




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.