Javascript request fullscreen is unreliable
Asked Answered
T

5

50

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!");
        }
    }
}
Tamelatameless answered 26/2, 2012 at 15:1 Comment(4)
It appears the second problem is intentional behaviour, apparently going to fullscreen is only allowed during user interaction. What's not clear is why even during interaction, going fullscreen only sometimes works.Tamelatameless
You function is working fine in Chrome 17 on ubuntu - I can't reproduce your first problem - maybe it's os specific issue.Bullivant
The current page goes to full screen, but when i navigate to the next pages.. through other hyperlinks, It again goes back to the normal mode why?Terat
@karthi, all the information on this page is from a year ago, all the browsers have been updated since then. If you have issues with the current browsers I suggest you ask a new question.Tamelatameless
L
96

requestFullscreen() can not be called automatically is because of security reasons (at least in Chrome). Therefore it can only be called by a 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.

Lotic answered 17/3, 2012 at 4:46 Comment(10)
At least in Firefox, the above is true AND your code has to run under 1 sec or a fullscreen request will not be accepted either (see bugzilla.mozilla.org/show_bug.cgi?id=687687).Courtesan
Does that mean I cannot use a fullscreen() function in my click or key press functions?Malatya
@Daniel Cheung - Quite the opposite, you can only go into fullscreen programmatically in you click/keypress/etc. event handlers.Mycorrhiza
@Derek朕會功夫 Well, using Firefox Nightly, it still generates the error. It worked before though... Could it be because I'm using jQuery? :/Malatya
@Derek朕會功夫 Request for full-screen was denied because Element.mozRequestFullScreen() was not called from inside a short running user-generated event handler.Malatya
@Daniel How are you calling it? Are you using .addEventListener?Mycorrhiza
@Derek朕會功夫 yes, even this doesn't work: button.addEventListener("click", function(){var i = document.getElementsByTagName("body")[0]; i.mozRequestFullScreen();})Malatya
Interestingly, at least for me, chrome actually appears to let you call this from normal javascript "these days" whereas from (at least) FF and Safari it has to be called from an onclick handler or something.Osher
Confirmed Jan 2017 with Chrome. I receive the following warning when using JavaScript vid.webkitRequestFullScreen(); Failed to execute 'requestFullscreen' on 'Element': API can only be initiated by a user gesture.Cupulate
Too bad Chrome does not count clicking "OK" on an alert box as a user gesture.Adelleadelpho
G
31

I know this is quite an old question but it is still the top result in Google when searching for FireFox's error message when calling mozRequestFullScreen() from code that wasn't triggered by any user interaction.

Request for full-screen was denied because Element.mozRequestFullScreen() was not called from inside a short running user-generated event handler.

As already discussed this is a security setting and therefore is the correct behaviour in normal browser environment (end user machine).

But I am writting an HTML5-based digital signage application which runs under a controlled environment without any user interaction intended. It is vital for my apllication to be able to switch to fullscreen automatically.

Luckily FireFox offers a possibilty to remove this restriction on the browser, which is rather hard to find. I will write it here as future reference for everybody finding this page via the Google search as I did

On the about:config page search for the following key and set it to false

full-screen-api.allow-trusted-requests-only

For my digital signage application I also removed the prompt the browser shows when entering fullscren:

full-screen-api.approval-required

Hopefully this might save someone the hours I wasted to find these settings.

Gomulka answered 22/11, 2014 at 15:15 Comment(5)
This has helped me a lot, thank you so much for sharing!Aramanta
How can I set this 'false' programmaticaly in my application?Hyacinthe
@niraj For security reasons you cannot change FireFox's settings from Javascript run in the browser context. There are two options to change the settings programatically, how ever both must be executed on the client machine, outside of the browser process. Either create a user.js file for you're profile or create a bash script, that generates the preference files Both solutions are describes in detail in this postGomulka
@LukasZech you sound like you're creating a "desktop" or otherwise "standalone" app to install on computers in a certain place. You may be better served by something like Electron instead of a browser.Moreira
@AlejandroIglesias Today I would certainly use Electron for this project but back in 2014 that was simply not an option as Electron was in a very early stage back thenGomulka
E
9

You have nothing wrong with your function. In Firefox, if you call that function directly, it will prevent to for full-screen. As you know, Request for full-screen was denied because docElm.mozRequestFullScreen(); was not called from inside a short running user-generated event handler. So, You have to call the function on event such as onClick in Firefox.

<a href="#" onClick="DoFullScreen()">Full Screen Mode</a>
Evening answered 9/4, 2012 at 14:2 Comment(0)
H
4

Another unexpected issue with requestFullscreen() is that parent frames need to have the allowfullscreen attribute, otherwise Firefox outputs the following error:

Request for fullscreen was denied because at least one of the document’s containing elements is not an iframe or does not have an “allowfullscreen” attribute.

Aside from iframes, this can be caused by your page being within a frameset frame. Because frameset is deprecated, there is no support for the HTML5 allowfullscreen attribute, and the requestFullscreen() call fails.

The Firefox documentation explicitly states this on MDN, but I think it bears reiterating here, for developers who might not read the documentation first.... ahem

Only elements in the top-level document or in an with the allowfullscreen attribute can be displayed full-screen. This means that elements inside a frame or an object can't.

Heliotropin answered 10/1, 2017 at 15:54 Comment(0)
D
4

I realize this is an old post, but in case someone else finds this I'd like to add a few suggestions and sample code.

To help avoid this error...

Failed to execute 'requestFullscreen' on 'Element': API can only be initiated by a user gesture.

Don't test for the existence of requestFullscreen(), which is a method. Instead, test for the existence of a property like document.fullscreenEnabled.

Also consider the following...

  • Move your fullscreen check into its own function so you can reuse it.
  • Make DoFullScreen() reusable by passing the element you want to affect as a parameter.
  • Use a guard clause at the top of DoFullScreen() to exit out of the function immediately if the window is already in fullscreen mode. This also simplifies the logic.
  • Set a default value for your DoFullScreen() element parameter to ensure the requestFullscreen() method is always called on an existing element. Defaulting to document.documentElement will probably save you some keystrokes.
// Move your fullscreen check into its own function
function isFullScreen() { 
  return Boolean(
    document.fullscreenElement ||
      document.webkitFullscreenElement ||
      document.mozFullScreenElement ||
      document.msFullscreenElement
  );
}

// Make DoFullScreen() reusable by passing the element as a parameter
function DoFullScreen(el) { 
  // Use a guard clause to exit out of the function immediately
  if (isFullScreen()) return false;
  // Set a default value for your element parameter
  if (el === undefined) el = document.documentElement; 
  // Test for the existence of document.fullscreenEnabled instead of requestFullscreen()
  if (document.fullscreenEnabled) { 
    el.requestFullscreen();
  } else if (document.webkitFullscreenEnabled) {
    el.webkitRequestFullscreen();
  } else if (document.mozFullScreenEnabled) {
    el.mozRequestFullScreen();
  } else if (document.msFullscreenEnabled) {
    el.msRequestFullscreen();
  }
}

(function () {
  const btnFullscreenContent = document.querySelector(".request-fullscreen-content");
  const el = document.querySelector(".fullscreen-content");
  // Request the .fullscreen-content element go into fullscreen mode
  btnFullscreenContent .addEventListener("click", function (){ DoFullScreen(el) }, false);

  const btnFullscreenDocument = document.querySelector(".request-fullscreen-document");
  // Request the document.documentElement go into fullscreen mode by not passing element
  btnFullscreenDocument .addEventListener("click", function (){ requestFullscreen() }, false);
})();
Duston answered 4/3, 2022 at 22:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.