Page Visibility API

2023. 4. 24.

Page Visibility API

The Page Visibility API, as the name suggests, allows you to determine whether a page is currently visible to the user. More precisely, it tells you if the page can be seen on the monitor. There's no way to know if the user has their eyes closed or is looking elsewhere :)

Previously, onblur and onfocus events were used, but these events were more about determining if the page was active rather than its visibility.

That's why the Page Visibility API was introduced.

Why use it?

The Page Visibility API allows you to detect situations like:

  • The user switching to another browser tab
  • Minimizing the browser window
  • The webpage being hidden because another application window is overlapping it
  • The computer entering sleep mode

This way, you can detect whether the web page is visible on the monitor.

How to use it?

The Page Visibility API consists of two properties and one event.

document.hidden // true if the page is currently not visible to the user
document.visibilityState // 'visible' if the page can be seen by the user, 'hidden' otherwise

Here's how to add an event listener:

document.addEventListener("visibilitychange", () => {
  if (document.visibilityState === 'hidden') { // or document.hidden
    myVideo.stop();
  } else {
    myVideo.play();
  }
});

Simple, right?

With this, if the user switches tabs or the computer enters sleep mode, the event handler will execute, visibilityState will become hidden, and the video will pause. When the user returns, the event handler will execute again, visibilityState will become 'visible', and the video will resume playing from where it left off.

Where to use it?

It can primarily be used for performance optimization or improving user experience.

You can reduce unnecessary server costs. This applies to various situations, like preventing unnecessary server requests when the user is not actively using the page. For example, in a video playback service, you could switch to audio-only playback when the page is not visible.

Alternatively, you could pause audio or video content when visibility is lost and automatically resume playback when the user's visibility is regained.

You can execute heavy tasks like logging or client-side data processing and transmission when the user isn't looking, thereby avoiding negatively impacting the user experience unnecessarily.

For services that support user-to-user communication, like messengers, it could serve as a trigger to switch to an idle or away status.

In mobile environments, it could offer ways to save the user's data.

♥ Support writer ♥
with kakaopay

Creative Commons LicenseThis work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License.

shiren • © 2025Sungho Kim