Using the Page Visibility API for Detecting Your Page Is Being Viewed by the End User or Not
HTML5 have many new features. One such feature is the new visibility API. This API allows you to easily detect your page is active, and in addition, you can perform specific events if it’s active. In this article we will show you how implement this feature in your application.
Without worrying about browser compatibility for the moment. There is an event called visibilitychange that gets fired every time window focus changes. In addition, there is a property called document.hidden that will tell your page is visible or not.
For example, the following script will change the document title based on your page is active or not:
Some browsers still require prefixing, such as the Android 4.4 browser. For these browsers, a bit more code is required.
We need some code to detect whether a prefixed version of the property. The code below does exactly that. It loops through each vendor prefix and sees if it is present in the document object. If so, it returns the correct prefixed version: