exitFullscreen() function in javascript not working

i have a button to open full screen and one to close fullscreen

my code is like so

<!DOCTYPE html>
<html>
<head>
<title>Fullscreen example</title>
<script src="scripts.js"></script>
</head>
<body>
<h1>Heading</h1>
<p>Paragraph</p>
<button id="opnFlscrnBtn" onclick="openFullscreen()">open fullscreen mode</button>
<button id="clsFlscrnBtn" onclick="closeFullscreen()">exit fullscreen mode</button>
<label for="clsFlscrnBtn">you can also use the operating system default exit full screen button or gesture</label>
</body>
</html>

the javascript (in scripts.js)

function openFullscreen() {
  document.documentElement.webkitRequestFullscreen();
  document.documentElement.msRequestFullscreen();
  document.documentElement.mozRequestFullscreen();
  document.documentElement.requestFullscreen();
}
function closeFullscreen() {
  document.documentElement.webkitExitFullscreen();
  document.documentElement.msExitFullscreen();
  document.documentElement.mozExitFullscreen();
  document.documentElement.exitFullscreen();
}

the open full screen button works but when i hit the close full screen button it dosent do anything.

specs: samsung galaxy tab a, android 9, chrome 89

Answer

Two issues here:

  • requestFullscreen should be run on document.documentElement, while exitFullscreen should be run on document.
  • If you’re not on a webkit browser, the webkit function won’t exist (the first one you call), and your function will error out before it calls the other functions. So you have to check to see if they exist.

The basic code to fix these issues is here and below:

/* View in fullscreen */
function openFullscreen() {
  /* Get the documentElement (<html>) to display the page in fullscreen */
  let elem = document.documentElement;
  if (elem.requestFullscreen) {
    elem.requestFullscreen();
  } else if (elem.webkitRequestFullscreen) { /* Safari */
    elem.webkitRequestFullscreen();
  } else if (elem.msRequestFullscreen) { /* IE11 */
    elem.msRequestFullscreen();
  }
}

/* Close fullscreen */
function closeFullscreen() {
  if (document.exitFullscreen) {
    document.exitFullscreen();
  } else if (document.webkitExitFullscreen) { /* Safari */
    document.webkitExitFullscreen();
  } else if (document.msExitFullscreen) { /* IE11 */
    document.msExitFullscreen();
  }
}

Based on this and this, if you want complete browser support, you’ll also want to add a check for the moz prefixed functions, mozRequestFullScreen and mozCancelFullScreen.