← Lessons

quiz vs the machine

Gold1330

Frontend

The Page Visibility API

Detect when a tab is hidden so you can pause work and save resources.

3 min read · core · beat Gold to climb

Knowing when nobody is looking

The Page Visibility API tells you whether your page is currently visible or hidden, for example when the user switches tabs or minimises the window. This lets apps behave politely with resources.

  • document hidden is a boolean shortcut, true when not visible
  • document visibilityState is visible or hidden
  • The visibilitychange event fires whenever the state changes

Practical wins

  • Pause video, audio, or animations when hidden
  • Stop polling or expensive timers to save battery and data
  • Save draft state when the user leaves the tab
  • Resume activity when the page becomes visible again

A note on reliability

For saving important data before a tab closes, pair visibilitychange with care, since the unload event is unreliable on mobile. Many teams treat the page becoming hidden as the last safe moment to persist state.

Key idea

The Page Visibility API exposes document hidden and the visibilitychange event so apps pause expensive work and persist state when a tab is no longer visible.

Check yourself

Answer to earn rating on the learn ladder.

1. Which event tells you the tab changed between visible and hidden?

2. What is a good action to take when a page becomes hidden?