oddworks blog

Page Visibility API explained: document.hidden vs visibilityState

On this page
  1. Where the API is defined
  2. document.hidden vs visibilityState
  3. When a page becomes hidden
  4. The basic pattern
  5. Patterns that work
  6. Visibility vs focus
  7. What else changes in a hidden tab
  8. Testing your handler
  9. When users turn it off
  10. FAQ

The Page Visibility API tells a page whether the user can currently see it. document.visibilityState is a string that is either "visible" or "hidden", and document.hidden is the same state as a boolean (true when hidden). When the state changes, the browser fires a visibilitychange event on document. Read either property, listen for the event, and you have the whole API.

Where the API is defined

The API began as a standalone W3C specification. It now lives in the WHATWG HTML Living Standard, and the old W3C address (w3.org/TR/page-visibility/) redirects there. MDN's Page Visibility API page cites the HTML spec and marks the feature Baseline, available across browsers since July 2015.

The spec is short. Each document has a visibility state that is "hidden" or "visible". The visibilityState getter returns it, and the hidden getter returns true when it is "hidden". When the state changes, the browser updates it and fires visibilitychange at the document with bubbles set to true. The event is not cancelable, and it carries no payload: you read the new state from document.visibilityState.

Older articles list a third value, "prerender". The current spec defines only "visible" and "hidden", so don't branch on it.

document.hidden vs visibilityState

They report the same thing. Pick by readability:

Property Type Values Use it when
document.hidden boolean true, false You want a quick if (document.hidden)
document.visibilityState string "visible", "hidden" You log the state or compare it with something
console.log(document.hidden);          // false in the tab you're reading
console.log(document.visibilityState); // "visible"

Both are read-only. Assigning to them does nothing.

When a page becomes hidden

Per MDN and the visibilitychange reference, the page becomes hidden when the user:

  • switches to another tab
  • minimizes the browser window
  • navigates away or closes the tab
  • on mobile, switches from the browser to another app, or the screen turns off

Browsers may also treat a window that is completely covered by another window as hidden. That behaviour varies by browser and operating system, so don't depend on it either way.

Two cases that trip people up:

  • Clicking into another app while the browser window stays visible does not hide the page. The window loses focus (blur fires, document.hasFocus() returns false), but visibilityState stays "visible".
  • Iframes share the parent's state. An <iframe> hidden with display: none does not get its own visibilitychange. Its document is visible whenever the top-level page is.

A tab opened in the background (Ctrl-click or middle-click on a link) starts out hidden, so check the state on load instead of assuming "visible".

The basic pattern

document.addEventListener('visibilitychange', () => {
  if (document.visibilityState === 'hidden') {
    // Stop work the user can't see.
  } else {
    // Resume it.
  }
});

You can also assign document.onvisibilitychange = () => { ... }, but addEventListener lets several pieces of code listen without overwriting each other.

Patterns that work

Pause a player and resume only if it was playing

This is the pattern from MDN, and the one video sites use. The flag stops the page from starting a video the user had already paused.

const video = document.querySelector('video');
let playingWhenHidden = false;

document.addEventListener('visibilitychange', () => {
  if (document.hidden) {
    playingWhenHidden = !video.paused;
    video.pause();
  } else if (playingWhenHidden) {
    video.play();
  }
});

It is also why your video stops when you switch tabs. The video pillar post covers that from the viewer's side.

Stop polling while hidden

let timer = null;

async function refresh() {
  const res = await fetch('/api/status');
  render(await res.json());
}

function startPolling() {
  if (timer === null) timer = setInterval(refresh, 30_000);
}

function stopPolling() {
  clearInterval(timer);
  timer = null;
}

document.addEventListener('visibilitychange', () => {
  if (document.hidden) {
    stopPolling();
  } else {
    refresh();       // catch up right away
    startPolling();
  }
});

if (!document.hidden) startPolling();

render is your own function. Calling refresh() on return matters: the data is stale after a long absence, and waiting 30 seconds for the next tick looks broken.

Send analytics when the session probably ends

MDN calls the switch to hidden "the last event that's reliably observable by the page". Send end-of-session data there with navigator.sendBeacon(), which queues the request even if the page is being torn down. Don't rely on unload or beforeunload.

document.addEventListener('visibilitychange', () => {
  if (document.visibilityState === 'hidden') {
    navigator.sendBeacon('/analytics', JSON.stringify({ event: 'session_end' }));
  }
});

Check whether the page was ever hidden

The spec also records each change in the performance timeline as a visibility-state entry. The HTML spec currently notes support in one engine only (Chromium), so treat it as optional:

const entries = performance.getEntriesByType('visibility-state');
const wasHidden = entries.some((entry) => entry.name === 'hidden');

This helps when you report performance metrics: a page loaded in a background tab renders late for reasons that have nothing to do with your code.

Visibility vs focus

These are separate signals, and pages often combine them.

What the user does visibilityState document.hasFocus() Window blur
Switches to another tab "hidden" false fires
Minimizes the window "hidden" false fires
Clicks another app, browser still on screen "visible" false fires

Use visibility to decide whether to do work, and focus to decide whether the user is typing in your page. Don't use blur as a stand-in for "hidden": MDN warns that it fires whenever the window loses focus, even if the page is still on screen.

What else changes in a hidden tab

The API only reports the state. Separately, browsers cut back on what a hidden page can do. MDN lists the main ones:

  • requestAnimationFrame() callbacks stop in background tabs and hidden iframes. See requestAnimationFrame in background tabs.
  • Timers such as setTimeout are throttled, and Chrome adds a much stronger stage for pages hidden for several minutes. Background tab throttling explains the stages.
  • Tabs playing audio, and pages with an active WebSocket or WebRTC connection, are exempt from some of that throttling.

If you're testing a page, keep these apart. Code that checks document.hidden and code that silently stops because rAF paused look the same from the outside.

Testing your handler

You don't need a special tool. Paste this into the console, switch tabs for a few seconds, then come back:

document.addEventListener('visibilitychange', () => {
  console.log(new Date().toISOString(), document.visibilityState);
});

You should see hidden followed by visible. Minimize the window and you'll get the same pair. Click another app with the browser still on screen and nothing logs, because the page never became hidden.

Our live test page shows the same signals as a site would see them: visibility, focus and the timing gaps rAF leaves behind.

When users turn it off

Some users don't want a site to know when they leave, usually because a video or stream they're listening to stops. They can block the signal with a uBlock Origin filter, a userscript, or an extension such as Focus Spoofer (which we make), which keeps document.hidden false, blocks visibilitychange and keeps rAF running on the tabs the user picks. How to disable the Page Visibility API walks through all three.

For developers this means one thing: treat visibility as a hint for saving resources, not as a security boundary. The value comes from the browser, and the user controls the browser.

FAQ

What is the difference between document.hidden and document.visibilityState?

Nothing in what they report. document.hidden is a boolean and document.visibilityState is a string ("visible" or "hidden"). Both read the same underlying state.

Does visibilitychange fire when I switch windows?

Only if the page becomes hidden. Switching to another app while the browser window stays on screen fires blur on the window but leaves visibilityState as "visible". Minimizing the window does fire visibilitychange.

Is the prerender state still used?

No. The current HTML spec defines only "visible" and "hidden". Older articles mention "prerender" from an earlier version of the spec.

Do iframes get their own visibility state?

No. An iframe's document has the same visibility state as its parent page. Hiding the iframe with CSS does not change it.

Is the Page Visibility API supported everywhere?

Yes. MDN lists it as Baseline, supported across major browsers since 2015, and the visibilitychange event itself as widely available since 2021.

Keep reading