ArticleZip > How To Detect When A Page Exits Fullscreen

How To Detect When A Page Exits Fullscreen

Have you ever encountered the challenge of detecting when a web page exits fullscreen mode on your projects? Whether you are developing a sleek web application or a stunning website, this issue can be a tricky one to handle. But fret not! In this guide, we will walk you through a simple and effective way to detect when a page exits fullscreen using JavaScript.

To begin, let's understand a bit about the Fullscreen API. When a web page enters fullscreen mode, the browser sends a fullscreen change event that you can capture using JavaScript. However, when the page exits fullscreen, there is no direct event to detect this change. But fear not, we have a clever workaround for you.

The trick is to compare the screen width and height with the window's innerWidth and innerHeight properties. When these values are the same, it indicates that the page has exited fullscreen. Here's how you can implement this in your code:

Javascript

function isPageInFullscreen() {
    return (window.innerWidth === screen.width && window.innerHeight === screen.height);
}

document.addEventListener('fullscreenchange', () => {
    if (!document.fullscreenElement && !document.webkitFullscreenElement && !document.mozFullScreenElement && !document.msFullscreenElement) {
        if (!isPageInFullscreen()) {
            // Page has exited fullscreen
            console.log('Page has exited fullscreen');
        }
    }
});

In the code snippet above, we define a function `isPageInFullscreen()` that checks whether the window is in fullscreen mode by comparing the window dimensions with the screen dimensions. Then, we add an event listener for the `fullscreenchange` event to detect fullscreen changes. Inside the event listener, we check if the document is not in fullscreen and if the page has exited fullscreen using our custom function.

By using this approach, you can reliably detect when a page exits fullscreen and perform any necessary actions in your application. Whether it's updating the UI or triggering specific functions, having this functionality adds an extra layer of control and interactivity to your projects.

Remember to test your code across different browsers to ensure compatibility. While the Fullscreen API is well-supported in modern browsers, it's always a good practice to validate your implementation across various platforms.

In conclusion, detecting when a page exits fullscreen is a valuable skill to have in your web development toolkit. By leveraging JavaScript and the comparison of window dimensions, you can seamlessly handle this scenario in your projects with ease. So go ahead, implement this technique in your code, and say goodbye to the hassle of missing fullscreen exit events!