Skip to content
Tutorials Center
My learning

Topics

Lesson 108 of 156 ยท Browser APIs

Fullscreen, Page Visibility and Screen Wake Lock

Use the Fullscreen API, the Page Visibility API and the Screen Wake Lock API - request, exit, events, pausing work in hidden tabs, and re-acquiring locks.

Some browser APIs are big, with many objects and events. Others do one small job well. This lesson covers three of the small ones, and they share a theme: they all deal with the state of the page or the screen. The Fullscreen API makes an element fill the whole screen. The Page Visibility API tells you whether the user can currently see your page. The Screen Wake Lock API stops the screen from dimming while your app is doing something the user is watching.

Together they make video players, slide shows, games, recipe apps and dashboards feel like real applications. They also help you be a good citizen: a page that stops animating and polling when nobody is looking saves battery and bandwidth.

Sandbox limits. The live editors run pages inside a sandboxed frame. Fullscreen is blocked there unless the frame allows it, and Wake Lock needs a visible, focused, secure page. The demos handle this with feature checks and try/catch, so they show a friendly message instead of crashing. The same code works on your own site.

Fullscreen API

element.requestFullscreen() asks the browser to show that element (and its children) filling the screen. It returns a promise, and it must be called from a user gesture such as a click or key press. A page cannot go fullscreen on its own, which prevents spoofing and annoyance.

API Purpose
element.requestFullscreen() Enter fullscreen with this element
document.exitFullscreen() Leave fullscreen
document.fullscreenElement The element currently fullscreen, or null
document.fullscreenEnabled Whether the browser and page allow it at all
fullscreenchange event Fires on enter and exit (on the element and on document)
fullscreenerror event Fires when a request fails
:fullscreen CSS pseudo-class Style an element while it is fullscreen

The user can leave fullscreen at any time with the Escape key, so never assume you control the state. Always react to fullscreenchange to keep your button label and layout in sync, rather than updating them only when you call the API.

A fullscreen toggle that explains itself

A few more notes:

  • Fullscreen a container, not just the video. If you fullscreen only a <video>, the browser shows its own controls. If you fullscreen a wrapping <div> that includes your custom controls and captions, they stay visible.
  • Iframes need the allowfullscreen attribute (or allow="fullscreen") before their content may request it.
  • Safari on iPhone only supports fullscreen for <video> elements, with the older prefixed API (webkitEnterFullscreen). Treat fullscreen as optional there.
  • Keyboard lock and orientation. screen.orientation.lock("landscape") can be combined with fullscreen on some mobile browsers, but support varies.

Page Visibility API

When a user switches tabs, minimizes the window or locks their phone, your page is hidden. Browsers throttle timers and pause requestAnimationFrame() in hidden tabs, but your own code, such as a polling loop or a video, may still do wasteful work. The Page Visibility API lets you react.

  • document.visibilityState is "visible" or "hidden".
  • document.hidden is a boolean shortcut for visibilityState === "hidden".
  • The visibilitychange event fires on document whenever the value changes.
stateDiagram-v2
  [*] --> visible: page opens in the foreground
  visible --> hidden: tab switched, window minimized, screen locked
  hidden --> visible: user returns
  hidden --> [*]: tab closed

A page flips between visible and hidden; visibilitychange fires at each switch.

Typical things to do when the page becomes hidden: pause video and animations, stop polling, mute sounds, and save unsaved work. When it becomes visible again: resume, and refresh data that may have gone stale.

Pause work while the page is hidden

Notice the last lines: call your handler once at startup. A page opened with "open in background tab" starts out hidden, and no visibilitychange event fires for the starting state.

Do not rely on unload events

On phones, the browser may kill a hidden page without ever firing unload or beforeunload. The reliable moment to save data or send final analytics is therefore when the page becomes hidden:

JavaScript
// Read-only: send analytics when the user leaves or switches away
document.addEventListener("visibilitychange", () => {
  if (document.visibilityState === "hidden") {
    navigator.sendBeacon("/analytics", JSON.stringify({ seconds, clicks }));
  }
});

navigator.sendBeacon() queues a small POST that the browser delivers even if the page is closing. For the similar but different question "is the element within the viewport?", use an IntersectionObserver instead; visibility here is about the whole page.

Screen Wake Lock API

Phones and laptops dim and lock the screen after inactivity. That is exactly wrong for a recipe you are following with flour on your hands, a map, a presentation, a workout timer or a boarding pass at the gate. The Screen Wake Lock API lets a page ask the system not to dim the screen while it is visible.

JavaScript
// Read-only
const sentinel = await navigator.wakeLock.request("screen");
// ...later, when you are done:
await sentinel.release();

request("screen") returns a promise for a WakeLockSentinel. Its facts:

  • screen is the only type currently defined.
  • It needs a secure context (HTTPS) and a visible document. Requesting while hidden rejects with a NotAllowedError. The request can also be refused for other reasons, for instance when the battery is very low, so always use try/catch.
  • The browser releases the lock automatically when the page becomes hidden. The sentinel fires a release event and its released property becomes true. The lock does not come back by itself when the user returns.
  • A feature check is "wakeLock" in navigator.

That last point is the one that catches people out. A correct implementation keeps a "wanted" flag and re-acquires the lock on visibilitychange, tying all three topics of this lesson together. The demo below runs against a tiny fake of the document and the Wake Lock API, so you can see the sequence of events:

JS Re-acquiring a wake lock when the page returns

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In a real page the same structure looks like this, with navigator.wakeLock and document in place of the fakes:

JavaScript
// Read-only
let wakeLock = null;
let wanted = false;

async function acquire() {
  if (!("wakeLock" in navigator)) return;
  try {
    wakeLock = await navigator.wakeLock.request("screen");
    wakeLock.addEventListener("release", () => console.log("wake lock released"));
  } catch (error) {
    console.warn(`Wake lock failed: ${error.name}`);
  }
}

document.addEventListener("visibilitychange", () => {
  if (wanted && document.visibilityState === "visible" && (!wakeLock || wakeLock.released)) {
    acquire();
  }
});

Release the lock as soon as you no longer need it (the cooking timer finished, the video ended). Holding it forever drains the battery and users notice.

Putting it together

A video player is the classic example of all three. It enters fullscreen from a button, pauses (or lowers quality) when the tab is hidden, and holds a wake lock while the video plays so the screen does not dim mid-movie. Each API is optional, so wrap it in a feature check and degrade gracefully. If any of them is unavailable, the player still plays.

For long-running work that must continue even when hidden, such as syncing data, these APIs are the wrong tool; look at service workers for background tasks. And remember that timers are throttled in background tabs, so the Visibility API is also how you notice that your setInterval has stopped being accurate.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does element.requestFullscreen() fail when called on page load?

    Browsers require transient user activation for fullscreen, so pages cannot take over the screen unprompted.
  2. 2. Which event should you use to keep a fullscreen button's label correct, even when the user presses Esc?

    fullscreenchange fires whenever the state changes, whether you or the user caused it. Updating the UI there keeps it truthful.
  3. 3. What does document.visibilityState return when the user switches to another tab?

    The two values are 'visible' and 'hidden'. The visibilitychange event fires when the value changes.
  4. 4. What happens to a screen wake lock when the page is hidden and then shown again?

    The sentinel is released automatically when the page becomes hidden. Re-request it in a visibilitychange handler if you still need it.
  5. 5. Why is visibilitychange a better place to save data than unload on mobile browsers?

    Mobile browsers often terminate background pages silently, so the moment the page becomes hidden is the last reliable chance to save.

Summary

  • Fullscreen: element.requestFullscreen() (user gesture required), document.exitFullscreen(), document.fullscreenElement, the fullscreenchange event and the :fullscreen pseudo-class. Update your UI from the event, because the user can press Esc.
  • Page Visibility: document.visibilityState / document.hidden and the visibilitychange event. Pause polling, animation and media while hidden, run your handler once at startup, and save data when the page becomes hidden rather than on unload.
  • Screen Wake Lock: navigator.wakeLock.request("screen") returns a sentinel you release(). It needs HTTPS and a visible page, can be refused, and is dropped when the page is hidden, so re-acquire it on visibilitychange.
  • All three are optional enhancements: feature-detect them, wrap calls in try/catch, and make the app work without them.

Next: Dates and Times - work with moments in time, time zones and formatting.