Comments: For a long time, we have been missing a method to determine whether a user is browsing a specified tab. Have users visited other websites? Are they switching back?
Now, the page visibility interface in HTML5 provides programmers with a way to use the visibilitychange page event to determine the current page visibility status and execute some targeted tasks. In addition, the new document. hidden attribute can be used.
Document. hidden
This new document. hidden attribute shows whether the page is currently viewed by the user. The value is true or false.
Document. visibilityState
The value of visibilityState is either visible (indicating that the page is currently activated for the browser, and the window is not in the minimized state) or hidden (the page is not the currently activated tab page, or the window is minimized .), Or prerender (the page is re-generated and invisible to the user .).
Visibilitychange event
It is very easy to monitor page visibility changes:
The Code is as follows:
// Compatibility with various browsers
Var hidden, state, visibilityChange;
If (typeof document. hidden! = "Undefined "){
Hidden = "hidden ";
VisibilityChange = "visibilitychange ";
State = "visibilityState ";
} Else if (typeof document. mozHidden! = "Undefined "){
Hidden = "mozHidden ";
VisibilityChange = "incluvisibilitychange ";
State = "required visibilitystate ";
} Else if (typeof document. msHidden! = "Undefined "){
Hidden = "msHidden ";
VisibilityChange = "msvisibilitychange ";
State = "msVisibilityState ";
} Else if (typeof document. webkitHidden! = "Undefined "){
Hidden = "webkitHidden ";
VisibilityChange = "webkitvisibilitychange ";
State = "webkitVisibilityState ";
} </P> <p> // Add a listener to display status changes in the title.
Document. addEventListener (visibilityChange, function (){
Document. title = document [state];
}, False); </p> <p> // Initialization
Document. title = document [state];
The above code will modify the document. title value when the page visibility changes!
So when do we need to use the visibilitychange event? For example, if an embedded video is being played on your page, When you switch to another tab, the video on your tab should be automatically paused. When the user switches back, the video will continue playing. For example, if your page has an automatic refresh action, you should stop refreshing when the user switches to another tab, and continue the previous action when the user switches back.