The method of judging whether a user is browsing a page in HTML5

Time:2022-5-13

Now, the page visibility interface in HTML5 provides a method for programmers to use the visibilitychange page event to judge the visibility state of the current page and perform some tasks. There is also a new document The hidden attribute can be used.

document.hidden

This new document Hidden attribute, which displays 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 active tab of the browser, and the window is not in the minimized state), or hidden (the page is not the currently active tab page, or the window is minimized), Or prerender (the page is being regenerated and not visible to the user.)

Visibilitychange event

It’s easy to listen for changes in page visibility:

Copy 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”;
}</p>
document.addEventListener(visibilityChange, function() {
document.title = document[state];
}, false);</ p>
document.title = document[state];

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

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