DEV Community

Cover image for Fullscreen API
Matías López Díaz
Matías López Díaz

Posted on

Fullscreen API

Using Fullscreen API is really easy, but sometimes things do not work as you need, maybe you discover not work the same in all browsers. Keep reading to learn how to use it in different scenarios:

I exclude IE because nobody should use it in 2022

I only provide example code compatible with Chromium-based, Firefox, and Safari

Request fullscreen

document.documentElement.requestFullscreen();
Enter fullscreen mode Exit fullscreen mode

The above function is async!

Exit fullscreen

document.exitFullscreen();
Enter fullscreen mode Exit fullscreen mode

Ok! Nice works perfect, but this is the beginning! Fullscreen API it's not standardized in all browsers so you will need to use a prefix to maximize compatibility.


Compatibility

Today the majority of modern updated browsers can handle Fullscreen API without a prefix but let's do 100% compatible code.

const context = document.documentElement;
const requestFullscreen = context.requestFullscreen || context.webkitRequestFullscreen || context.mozRequestFullScreen;
const exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.mozCancelFullScreen;
Enter fullscreen mode Exit fullscreen mode

(Change context value to this in case you work with a web component)

Great! Now I only need to execute requestFullscreen and exitFullscreen to toggle!

Nope! You will get the following error:

TypeError: Failed to execute 'requestFullscreen' on 'Element': Illegal invocation

TypeError: Failed to execute 'exitFullscreen' on 'Element': Illegal invocation
Enter fullscreen mode Exit fullscreen mode

This is because the reference of context (DOM element) will not works, so we will need to bind the context:

requestFullscreen.bind(document.documentElement)();
exitFullscreen.bind(document)();
Enter fullscreen mode Exit fullscreen mode

In case you want to use it inside of web component:

requestFullscreen.bind(this)();
exitFullscreen.bind(document)();
Enter fullscreen mode Exit fullscreen mode

Full working toggle Fullscreen

function toggleFullscreen() {
    const requestFullScreen = this.requestFullscreen || this.webkitRequestFullscreen || this.mozRequestFullScreen;
    const exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.mozCancelFullScreen;
    const isFullscreen = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement;
    if (isFullscreen) return exitFullscreen.bind(document)();
    else if (!isFullscreen) return requestFullScreen.bind(this)();
}
toggleFullscreen.bind(document.documentElement)(); // Typical way
toggleFullscreen.bind(this)(); // Inside web component
Enter fullscreen mode Exit fullscreen mode

Top comments (0)