Home  >  Article  >  Web Front-end  >  How to determine whether the user is browsing the page in HTML5_html5 tutorial skills

How to determine whether the user is browsing the page in HTML5_html5 tutorial skills

WBOY
WBOYOriginal
2016-05-16 15:47:531705browse

Now, the page visibility interface in HTML5 provides programmers with a method that allows them to use the visibilitychange page event to determine the visibility status of the current page and perform certain tasks in a targeted manner. There is also a new document.hidden property available.

document.hidden

This new document.hidden attribute shows whether the page is the page 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 the currently activated tab of the browser, and the window is not minimized), or hidden (the page is not the currently activated tab page, or the window is minimized.), or prerender (the page Regenerating, not visible to the user ).

visibilitychange event

Listening to page visibility changes is very easy:

Copy the code
The code is as follows:

// Compatible 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 = "mozvisibilitychange";
state = "mozVisibilityState";
} else if (typeof document.msHidden !== "undefined") {
hidden = "msHidden";
visibilityChange = "msvisibilitychange";
state = "msVisibilityState";
} else if (typeof document.webkitHidden !== "undefined") {
hidden = "webkitHidden";
visibilityChange = "webkitvisibilitychange";
state = "webkitVisibilityState";
}

//Add a listener to display status changes in the title
document.addEventListener(visibilityChange, function() {
document.title = document[state];
}, false);

//Initialization
document.title = document[state];


The above code will modify the value of document.title when the page visibility changes!

So, when do you need to use the visibilitychange event? For example, if you have an embedded video playing on your page, when the user switches to another tab, the video on your tab should automatically pause and resume playing when the user switches back. For another example, if your page has an automatic refresh action, when the user switches to another tab, you should stop refreshing, and continue the previous action when the user switches back.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn