Home  >  Article  >  Web Front-end  >  Chat: HTML 5 page visibility API_html/css_WEB-ITnose

Chat: HTML 5 page visibility API_html/css_WEB-ITnose

WBOY
WBOYOriginal
2016-06-24 11:55:021096browse

Translation source: http://www.ido321.com/1126.html

Original text: HTML5 Page Visibility API

Translation: HTML 5 pages can Visual API

Translator: dwqs

In the early days, browsers did not provide tabs, but now basically all browsers do this function. As a programmer, I usually have 10 to 15 tabs open at the same time, and sometimes 25 to 30.

Why introduce the Page Visibility API?

Before, it was impossible to determine which tab was active and which was not, but with the help of HTML 5 Visibility API, it is possible to detect whether the user is browsing a page of a website.

In this article, we will understand how to use the HTML 5 Visibility API and use a small demo to discover the status of the page. In this demo, the title of the document will pop up based on the visibility status of the page.

Check the visibility of the page

In order to use the Visibility API, we need to first understand two new document properties, the first is document.visibilityState and the other is document.hidden. Their functions are different.

document.visibilityState has four different values:

1. hidden: the page is not visible on any screen

2. prerender: the page is loading, not visible to the user Visible

3. visible: the page is visible

4. unloaded: the page is unloaded (that is, the user will leave the current page)

document.hidden is a Boolean value, false means the page Visible, true means the page is not visible.

Now that you know the available attributes, it’s time to listen for events, so that you can know what the visibility status of the page is. This is done using the visibilitychange event. The example is as follows:

document.addEventListener('visibilitychange', function(event) {  if (!document.hidden) {    // The page is visible.  } else {   // The page is hidden.  }});

This code is a simple application of the visibilitychange event? Detection The status of the current page. But what you must know is that all properties and methods must be prefixed because they are privately prefixed in some browsers. The following is a cross-browser case:

// Get Browser-Specifc Prefixfunction getBrowserPrefix() {     // Check for the unprefixed property.  if ('hidden' in document) {    return null;  }   // All the possible prefixes.  var browserPrefixes = ['moz', 'ms', 'o', 'webkit'];   for (var i = 0; i < browserPrefixes.length; i++) {    var prefix = browserPrefixes[i] + 'Hidden';    if (prefix in document) {      return browserPrefixes[i];    }  }   // The API is not supported in browser.  return null;} // Get Browser Specific Hidden Propertyfunction hiddenProperty(prefix) {  if (prefix) {    return prefix + 'Hidden';  } else {    return 'hidden';  }} // Get Browser Specific Visibility Statefunction visibilityState(prefix) {  if (prefix) {    return prefix + 'VisibilityState';  } else {    return 'visibilityState';  }} // Get Browser Specific Eventfunction visibilityEvent(prefix) {  if (prefix) {    return prefix + 'visibilitychange';  } else {    return 'visibilitychange';  }}

Now that you have prefixed properties and methods in all browsers, you can apply them with confidence. Make adjustments to the previous code:

// Get Browser Prefixvar prefix = getBrowserPrefix();var hidden = hiddenProperty(prefix);var visibilityState = visibilityState(prefix);var visibilityEvent = visibilityEvent(prefix); document.addEventListener(visibilityEvent, function(event) {  if (!document[hidden]) {    // The page is visible.  } else {   // The page is hidden.  }});

Where do I need to use the Visibility API?

In the following situations, you can consider using the API:

1. You are browsing a navigation page, and this page is querying details from an RSS source, or calling it regularly API, if the page is not visible to users,

We can limit calls to RSS feeds or APIs.

2. For common hand-style effects, when the page is invisible, its movement can be restricted.

3. In the same way, HTML Notification (Translation: http://www.ido321.com/1130.html) is displayed to the user only when the page is invisible.

We already know how the code calls the Visibility API, let’s take a look at a Demo.

Demo

Demo1: Use the Visibility API to change the page title: View Demo

Demo2: When the page is not visible, how to limit the query from the server transmitted data.

In Demo2, how will we limit the query for refresh information from the server? Not only is the user browsing the page, but also assuming that the page has introduced

JQuery. For simplicity, only counts are shown, but real server data can be used instead.

HTML:

<!-- This element will show updated count --><h1 id="valueContainer">0</h1>

JavaScript:

<script type="text/javascript">         // Get Browser Prefix    var prefix = getBrowserPrefix();    var hidden = hiddenProperty(prefix);    var visibilityState = visibilityState(prefix);    var visibilityEvent = visibilityEvent(prefix);         var timer = null;         function increaseVal() {        var newVal = parseInt($('#valueContainer').text()) + parseInt(1);        $('#valueContainer').text(newVal);        document.title = newVal + ': Running';                 timer = setTimeout(function() {            increaseVal();        }, 1);    }         // Visibility Change    document.addEventListener(visibilityEvent, function(event) {          if (document[hidden]) {              clearTimeout(timer);              var val = parseInt($('#valueContainer').text());              document.title = val + ': Pause';          } else {              increaseVal();           }    });         increaseVal();     </script>

View Demo

Browser Support

If you want to know whether the browser supports the Visibility API, I recommend going to Can I use? to check. However, it is recommended to use programming to detect whether the browser supports it. You can refer to Detect Support for Various HTML5 Features (Translation:

http://www.ido321.com/1116.html). There is already good support for this API in mainstream modern browsers

Summary

As I said, there is a nice API for us to use that contains two properties and an event. It can be easily integrated into your existing applications and can bring a great user experience. The last thing I want to say is that when the page is invisible to the user, we can control the behavior of the page.

Next article: Miscellaneous talk: HTML 5 message notification mechanism

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