Skip to content
Tutorials Center
My learning

Topics

Lesson 101 of 122 ยท Web APIs

Page Visibility, Fullscreen and Screen Wake Lock

React when a tab is hidden with the Page Visibility API, take over the screen with the Fullscreen API, and keep a device awake with Screen Wake Lock.

Three browser APIs help a page behave well in the physical world. The Page Visibility API tells you when the user switches to another tab or minimizes the window, so you can stop wasting battery on work nobody is watching. The Fullscreen API lets an element, such as a video, a game or a slide, fill the whole screen. The Screen Wake Lock API stops the screen from dimming and locking while someone follows a recipe, reads a long document or watches a presentation.

They fit together naturally: when the page is hidden you pause things and a wake lock is released, and when it comes back you resume. As with the other APIs in this chapter (see Introduction to Web APIs), some of them need a secure context, a user gesture or a permission policy, and the examples here are written to handle refusal gracefully.

The Page Visibility API

A tab is visible when the user can see it, and hidden when it is in a background tab, the window is minimized or the screen is locked. The API gives you two things on the document:

  • document.visibilityState is either "visible" or "hidden".
  • document.hidden is a shortcut: true when the state is "hidden".

When the state changes, the browser fires a visibilitychange event on document:

JavaScript
document.addEventListener('visibilitychange', () => {
  if (document.visibilityState === 'hidden') {
    pauseEverything();
  } else {
    resumeEverything();
  }
});
stateDiagram-v2
    [*] --> Visible: page opens in front
    Visible --> Hidden: switch tab, minimize or lock screen
    Hidden --> Visible: return to the tab
    Hidden --> [*]: tab is closed

The page is either visible or hidden; the visibilitychange event fires on every switch.

What to do when the page is hidden

Browsers already slow down background tabs: timers are throttled and animation frames stop. You should help by deliberately pausing:

  • Animations, games and videos that no one is watching (but not audio the user wants to keep hearing).
  • Polling a server every few seconds. Stop, and refresh once when the tab returns.
  • Live counters and carousels, so that a rotating banner does not jump through ten slides on return.

The hidden state is also the best moment to save data. Mobile browsers often discard background tabs without warning, and the old unload event is unreliable, so visibilitychange is the last dependable chance to store a draft or send analytics. Use navigator.sendBeacon() for small messages, because it keeps going even as the page goes away:

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

Run the next example, then switch to another browser tab for a few seconds and come back. The clock stops counting while the tab is hidden, and the log records each switch.

A clock that pauses when hidden

Visibility is about the tab, not about whether the page is scrolled out of view. To know whether a single element is on screen (for lazy loading, say), use the IntersectionObserver API instead.

The Fullscreen API

The Fullscreen API makes one element cover the entire screen, hiding the browser's own toolbars. It is perfect for video players, image galleries, maps, presentations and games.

You ask with element.requestFullscreen(), which returns a promise, and you leave with document.exitFullscreen(). The important properties and events are:

Name Meaning
element.requestFullscreen() Asks to show that element fullscreen.
document.exitFullscreen() Leaves fullscreen.
document.fullscreenElement The element currently fullscreen, or null.
document.fullscreenEnabled true if the page is allowed to use fullscreen at all.
fullscreenchange event Fires on every entry and exit.
fullscreenerror event Fires when a request fails.

The request must come from a user gesture, such as a click or key press; a script cannot force fullscreen on page load. The user can always leave with the Esc key, and the browser shows a short hint saying so. That is a safety feature you cannot disable.

JavaScript
const stage = document.getElementById('stage');
const toggle = document.getElementById('fullscreen-toggle');

toggle.addEventListener('click', async () => {
  try {
    if (document.fullscreenElement) {
      await document.exitFullscreen();
    } else {
      await stage.requestFullscreen();
    }
  } catch (error) {
    console.error('Fullscreen failed:', error.name);
  }
});

document.addEventListener('fullscreenchange', () => {
  toggle.textContent = document.fullscreenElement ? 'Exit fullscreen' : 'Go fullscreen';
});

Some points that trip people up:

  • Pick the element carefully. Fullscreen the <div> that holds both the video and your own controls, not just the <video>, or your controls disappear. (A <video controls> has its own fullscreen button, as covered in Video.)
  • Iframes need permission. A page inside an <iframe> can only use fullscreen when the iframe has allow="fullscreen". See Iframes. The sandboxed editors on this site do not allow it.
  • Style the fullscreen state with CSS. The :fullscreen pseudo-class matches the element that is fullscreen, and ::backdrop styles the layer behind it.
  • Browser differences. Desktop browsers and iPad support fullscreen for any element. On iPhone, Safari supports it only for videos, so keep a fallback layout.
CSS
#stage:fullscreen {
  background: #000;
  display: grid;
  place-items: center;
}

The following example wires up a stage with a button. Here the request is refused, because the sandbox does not allow fullscreen, so you will see the fallback message. On your own page, with no sandbox, the same code would work.

A fullscreen button with a fallback

Checking document.fullscreenEnabled first, as the example does, lets you disable or hide the button instead of showing one that cannot work.

The Screen Wake Lock API

Phones and laptops dim and lock the screen after a period without touch or key input. That is annoying when someone is following a recipe, reading sheet music, watching a slideshow or showing a boarding pass. The Screen Wake Lock API lets your page ask the system to keep the screen on.

You request a lock with navigator.wakeLock.request('screen'). The promise resolves to a sentinel object. Keep a reference to it, because releasing the lock means calling sentinel.release():

JavaScript
let wakeLock = null;

async function keepAwake() {
  try {
    wakeLock = await navigator.wakeLock.request('screen');
    wakeLock.addEventListener('release', () => {
      console.log('Wake lock was released');
    });
  } catch (error) {
    console.log('Could not keep the screen on:', error.name);
  }
}

async function allowSleep() {
  if (wakeLock) {
    await wakeLock.release();
    wakeLock = null;
  }
}

What you must know:

  • It needs a secure context, and the page must be visible when you request the lock.
  • The request can fail, for example with NotAllowedError, when the device is in battery-saver mode or a policy forbids it. Inside an iframe, the parent must allow the screen-wake-lock permission policy.
  • Only the value 'screen' exists today.
  • The browser releases the lock automatically when the page becomes hidden. When the user returns, the lock is gone, and you must request it again. This is where the Page Visibility API comes back in:
JavaScript
document.addEventListener('visibilitychange', async () => {
  if (wakeLock !== null && document.visibilityState === 'visible') {
    // The old sentinel was released when the page was hidden.
    await keepAwake();
  }
});

Hold the lock only while it is truly needed: a recipe being followed, a video playing. Releasing it as soon as the task ends is both polite and good for battery life. A wake lock never needs a user prompt, but a request tied to a button press is a clear way to show what is happening, as in the example below.

A wake lock switch

In the sandbox, the lock is refused or unavailable and the message explains it. In a normal page on HTTPS, checking the box would keep the screen awake until you uncheck it or leave the tab.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which event tells you that the user switched to another tab?

    visibilitychange fires whenever document.visibilityState switches between visible and hidden. It is more reliable than unload, especially on mobile.
  2. 2. Why might requestFullscreen() be rejected when you call it on page load?

    Fullscreen requires transient user activation. A script cannot take over the screen without the user doing something first.
  3. 3. A wake lock was active, the user switches tabs and later comes back. What is the state?

    Wake locks are released automatically when the page is hidden. Listen to visibilitychange and request a new lock when the page is visible again.
  4. 4. You want a custom control bar to stay visible in fullscreen. Which element should you make fullscreen?

    Only the fullscreen element and its descendants are shown. Wrapping the video and its controls together keeps your own controls on screen.

Summary

  • document.visibilityState and the visibilitychange event tell you when a tab is hidden; pause animations and polling there, and save data with sendBeacon().
  • element.requestFullscreen() needs a user gesture and returns a promise. Check document.fullscreenEnabled, listen to fullscreenchange, style with :fullscreen, and remember that iframes need allow="fullscreen".
  • navigator.wakeLock.request('screen') returns a sentinel that you must release(); requests can be refused.
  • The browser drops a wake lock whenever the page is hidden, so re-acquire it on visibilitychange.
  • Always provide a fallback for when an API is missing or refused.

Next lesson: Camera, Microphone and MediaRecorder, where you capture live audio and video and record it in the browser.