Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript request fullscreen is unreliable

Tags:

javascript

I'm trying to use the JavaScript FullScreen API, using workarounds for current non-standard implementations from here:

https://developer.mozilla.org/en/DOM/Using_full-screen_mode#AutoCompatibilityTable

Sadly, it behaves very erratically. I only care about Chrome (using v17), but since I was having problems I did some tests in Firefox 10 for comparison, results are similar.

The code below attempts to set the browser to fullscreen, sometimes it works, sometimes not. It ALWAYS calls the alert to indicate it is requesting fullscreen. Here's what I've found:

  • It USUALLY sets fullscreen. It can get to a state where this stops working, but the alert still happens, i.e. it is still requesting FullScreen, but it doesn't work.
  • It can work if called from a keypress handler (document.onkeypress), but not when called on page loading (window.onload).

My code is as follows:

function DoFullScreen() {      var isInFullScreen = (document.fullScreenElement && document.fullScreenElement !==     null) ||    // alternative standard method               (document.mozFullScreen || document.webkitIsFullScreen);      var docElm = document.documentElement;     if (!isInFullScreen) {          if (docElm.requestFullscreen) {             docElm.requestFullscreen();         }         else if (docElm.mozRequestFullScreen) {             docElm.mozRequestFullScreen();             alert("Mozilla entering fullscreen!");         }         else if (docElm.webkitRequestFullScreen) {             docElm.webkitRequestFullScreen();             alert("Webkit entering fullscreen!");         }     } } 
like image 251
Stefan Avatar asked Feb 26 '12 15:02

Stefan


1 Answers

requestFullscreen() can not be called automatically is because of security reasons (at least in Chrome). Therefore it can only be called by an user action such as:

  • click (button, link...)
  • key (keydown, keypress...)

And if your document is contained in a frame:

  • allowfullscreen needs to be present on the <iframe> element*

* W3 Spec:
"...To prevent embedded content from going fullscreen only embedded content specifically allowed via the allowfullscreen attribute of the HTML iframe element will be able to go fullscreen. This prevents untrusted content from going fullscreen..."

Read more: W3 Spec on Fullscreen

Also mentioned by @abergmeier, on Firefox your fullscreen request must be executed within 1 second after the user-generated event was fired.

like image 156
Derek 朕會功夫 Avatar answered Sep 22 '22 16:09

Derek 朕會功夫