How to go fullscreen in JavaScript
There are occasions where we want to present a video or image fullscreen to the user. At the least, we want to provide an option to view in fullscreen. Let's see how can we achieve the same.
Fullscreen API to the rescue
Browser's fullscreen API adds methods to all elements in order to present them in full-screen mode and exit the same upon request.
Checking the fullscreen support
It is better to check the permissions first whether the window instance supports fullscreen mode or not.
const fullscreenEnabled = document.fullscreenEnabled|| document.mozFullscreenEnabled|| document.webkitFullscreenEnabled;
It is always good to check those permissions in advance to act on it and request the same if it not enabled or given.
Requesting fullscreen
Using the below, we get the supported and available full screen function.
const requestFullscreen =element.requestFullscreen ||element.mozRequestFullscreen ||element.webkitRequestFullScreenrequestFullscreen().then(() => console.log("We are full ^_^")).catch(() => console.error("Can't go full T_T"));
element
can be any element. To full screen the entire window usedocument.documentElement.requestFullscreen()
.
Exiting fullscreen
Same as above, we get the exit full screen function to bring the window back to normal.
const exitFullscreen = document.exitFullscreen|| document.mozExitFullscreen|| document.webkitExitFullscreenexitFullscreen().then(() => console.log("We are out O_o")).catch(() => console.error("Can't get out O_O"));
Notice that
exitFullscreen
is always called and available only on thedocument
level.
What do you think happens when we use F11 to go fullscreen?