Use the javascript Page Visibility API to determine whether the user has closed the browser window (html page)

Page Visibility API

Introduction

Sometimes, developers need to know that the user is leaving the page. The common method is to listen for the following three events.

  • pagehide
  • beforeunload
  • unload

However, these events may not fire on the phone, and the page just closes. Because the mobile phone system can directly transfer a process to the background and then kill it.

  • The user clicks on a system notification to switch to another app.
  • The user enters the task switching window and switches to another App.
  • The user clicked the Home button to switch back to the home screen.
  • The operating system automatically switches to another app (for example, when a phone call is received).

The above situations will cause the mobile phone to switch the browser process to the background, and then in order to save resources, the browser process may be killed.

Previously, the page was switched by the system and the system cleared the browser process, which could not be monitored. The developer wants to specify the code that will be executed in any kind of page unload situation, which is also impossible. To solve this problem, the Page Visibility API was born. In all cases, mobile or desktop, this API will listen for changes in the visibility of the page.

The significance of this new API is that by monitoring the visibility of web pages, it can predict the unloading of web pages, and can also be used to save resources and slow down power consumption. For example, once the user does not view the webpage, the following webpage behaviors can be suspended.

  • polling the server
  • web animation
  • The audio or video that is playing

document.visibilityState

This API mainly adds a document.visibilityState property to the document object. This property returns a string representing the current visibility state of the page, with three possible values.

The post Using the javascript Page Visibility API to determine if the user has closed the browser window (html page) first appeared on Lenix Blog .

This article is reprinted from https://blog.p2hp.com/archives/9316
This site is for inclusion only, and the copyright belongs to the original author.

Leave a Comment