Now, the HTML5 page visibility interface gives programmers a way to use Visibilitychange page events to determine the state of the current page visibility and to perform certain tasks in a targeted manner. There are also new Document.hidden properties that can be used.
Document.hidden
This new Document.hidden property, which shows whether the page is the page that the user is currently viewing, with a value of ture or false.
Document.visibilitystate
The value of visibilitystate is either visible (indicates that the page is currently active tab for the browser, and the window is not minimized), or hidden (the page is not the active tab page, or the window is minimized.) ), or PreRender (the page is regenerated, not visible to the user.) ).
VIsibilitychange Event
Monitoring page Visibility changes is easy:
The code is as follows:
- Various browser compatible
- 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 listener to display status changes in title
- Document.addeventlistener (Visibilitychange, function () {
- Document.title = Document[state];
- }, false); //Initialize
- Document.title = Document[state];
The above code modifies the value of document.title when the visibility of the page changes!
So, when do you need to use the Visibilitychange event? For example, if you have an embedded video on your page that is playing, when the user switches to another tab, the video on your tab should automatically pause and continue playing when the user switches back. For example, if your page has an automatic refresh action, when the user switches to another tab, you should stop the refresh and continue the previous action when the user switches back.
Reprint Please specify: Code Academy >Web Front end > HTML tutorial > How to use HTML5 to determine whether a user is viewing a page
Use HTML5 to determine if a user is browsing page tips