How to detect browser has gone to full screen

Use fullscreenchange event to detect a fullscreen change event, or if you don't want to handle vendor prefixes than you can also listen to the resize event (the window resize event that also triggers when fullscreen is entered or exited) and then check if document.fullscreenElement is not null to determine if fullscreen mode is on. You'll need to vendor prefix fullscreenElement accordingly. I would use something like this:

var fullscreenElement = document.fullscreenElement || document.mozFullScreenElement ||
document.webkitFullscreenElement || document.msFullscreenElement;

https://msdn.microsoft.com/en-us/library/dn312066(v=vs.85).aspx has a good example for this which I quote below. They have used the fullscreenChange event, but you could listen for the "resize" event

document.addEventListener("fullscreenChange", function () {
          if (fullscreenElement != null) {
              console.info("Went full screen");
          } else {
              console.info("Exited full screen");              
          }
      });

After trying a lot of approaches across different browsers and devices, the following solution worked for me reliably.

 window.addEventListener("resize", () => {
        setTimeout(() => {
            const windowWidth = window.innerWidth * window.devicePixelRatio;
            const windowHeight = window.innerHeight * window.devicePixelRatio;
            const screenWidth = window.screen.width;
            const screenHeight = window.screen.height;
            console.log(windowWidth/screenWidth);
            console.log(windowHeight/screenHeight);
            if (((windowWidth/screenWidth)>=0.95) && ((windowHeight/screenHeight)>=0.95)) {
                console.log("Fullscreen");
            }
            else {
                console.log("Not Fullscreen");
            }
        }, 100);
    })

I haven't tested this for reliability but this is my take.

  //without jQuery
window.addEventListener('resize', function(){
  if(screen.width === window.innerWidth){
   // this is full screen
  }
});


  //with jQuery
$(document).ready(function() {
  $(window).on('resize', function(){
    if(screen.width === window.innerWidth){
      // this is full screen
    }
  });
});

This seems to work when pressing the F11 button and other methods, so it should catch the edge cases that the full screen api does not. Although I'm not sure the comparison of screen.width vs. window.innerWidth is a reliable way to check for full screen. Maybe someone else can add to/critique this.

Tags:

Javascript