Fullscreen API
Matías López Díaz
Posted on June 6, 2022
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();
The above function is async!
Exit fullscreen
document.exitFullscreen();
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;
(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
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)();
In case you want to use it inside of web component:
requestFullscreen.bind(this)();
exitFullscreen.bind(document)();
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
Posted on June 6, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.