0

why cant i trigger fullscreen by just running a function? (dont suggest functions) my problem is that running a perfectly correct function to trigger fullscreen onclick totally works but if i run the function by itself it dosent trigger fullscreen. is this a user consent problem because the browser or the developers of these web programming languages dont let you do certain things without user consent?

General Grievance
  • 4,555
  • 31
  • 31
  • 45
somebody
  • 97
  • 10
  • Does this answer your question? [How to exit fullscreen onclick using Javascript?](https://stackoverflow.com/questions/36672561/how-to-exit-fullscreen-onclick-using-javascript) – Heretic Monkey Apr 14 '21 at 15:59
  • Can you exchange your code with this: https://www.w3schools.com/jsref/met_element_exitfullscreen.asp Might be you run in some sort of js error on specific devices/browsers. In your case you should always check if the function you want to use exists. – sbrand5020 Apr 14 '21 at 15:33
  • well its the exact same code – somebody Apr 14 '21 at 15:37
  • its not. They check if the function exists. give it a try – sbrand5020 Apr 14 '21 at 15:38

1 Answers1

0

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.

Nisala
  • 1,313
  • 1
  • 16
  • 30