Page visibility and full-screen mode WEB API  | Web Development for Beginners

Page visibility and full-screen mode WEB API | Web Development for Beginners

·

2 min read

Hey, learners and beginners here are my latest post, where we gonna learn about the Page visibility and Full-Screen Mode WEB API.

Page visibility Web API

PageVisibility API is used for detecting the visibility of the page. The document object provides properties and event listeners to detect the page visibility.

This API is useful for

  • Handling auto pause & play of video or animations
  • Avoid playing distracting sounds when a user is not focused on the tab
  • Stop polling or refreshing data on the page when not visible
  • Switch image in carousel only when a page is visible

Properties

The document provides two properties to find page visibility.

  • hidden(boolean): Boolean value will be true if page is hidden
  • visibilityState: Represents the state of visibility. Has two possible value.
    • visible: Page is visible
    • hidden: Page is hidden

Event

An event visibilitychange will be fired on document object when page visibility changes

document.addListener('visibilitychange', handler);

Play or pausevideo on page visibility change

function handler() { 
    if (document.hidden) {
        document.getElementById('video').pause();
    } else {
        document.getElementById('video').play(); 
    }
}

FullScreen Mode Web API

Fullscreen mode can be achieved in a web page using the API provided on the HTML element.

An HTML element like a video can be viewed in fullscreen mode by using requestFullscreen() method.

Fullscreen API works on standard HTML elements. It doesn't work on <dialog> element and elements inside iFrame where iFrame doesn't have allowfullscreen attribute set.

Request Fullscreen

requestFullscreen() accepts a single parameter and returns a promise.

{ navigationUI: 'auto' | 'hide' | 'show' }

  • hide: The browser's navigation interface will be hidden.
  • show: The browser will present page navigation controls and possibly other user interfaces
  • auto: The browser will choose which of the above settings to apply. This is the default value.

Example

<video id="video" width="320" height="240" controls>
   <source src="src-video" type="video/mp4">
</video>
document
  .getElementById("video")
  .requestFullscreen()
  .catch((err) => console.log("Couldn't open in fullscreen mode"));

EXIT FULLSCREEN

Exit form fullscreen mode is achieved by using exitFullscreen() method on doocument object document.exitFullscreen()

Document object has two event handlers changes in fullscreen.

  • document.onfullscreenchange : emits events, that represents transition between fullscreen mode or not.
  • document.onfullscreenerror : Error handler for fullscreen error event.

That's it. ⚡Thanks For Reading | Happy Coding 😎

Did you find this article valuable?

Support Rahul by becoming a sponsor. Any amount is appreciated!