46

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!");
        }
    }
}
Stefan
  • 8,819
  • 10
  • 42
  • 68
  • 1
    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. – Stefan Feb 26 '12 at 20:23
  • You function is working fine in Chrome 17 on ubuntu - I can't reproduce your first problem - maybe it's os specific issue. – WTK Feb 29 '12 at 13:58
  • 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? – karthi Apr 02 '13 at 04:51
  • @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. – Stefan Apr 02 '13 at 08:04

5 Answers5

91

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.

starball
  • 20,030
  • 7
  • 43
  • 238
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
  • 2
    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 https://bugzilla.mozilla.org/show_bug.cgi?id=687687). – abergmeier Jan 04 '14 at 17:54
  • Does that mean I cannot use a `fullscreen()` function in my click or key press functions? – Daniel Cheung Feb 09 '16 at 03:52
  • @Daniel Cheung - Quite the opposite, you can only go into fullscreen programmatically in you click/keypress/etc. event handlers. – Derek 朕會功夫 Feb 09 '16 at 03:57
  • @Derek朕會功夫 Well, using Firefox Nightly, it still generates the error. It worked before though... Could it be because I'm using jQuery? :/ – Daniel Cheung Feb 09 '16 at 04:00
  • 3
    @Derek朕會功夫 `Request for full-screen was denied because Element.mozRequestFullScreen() was not called from inside a short running user-generated event handler.` – Daniel Cheung Feb 09 '16 at 04:01
  • @Daniel How are you calling it? Are you using `.addEventListener`? – Derek 朕會功夫 Feb 09 '16 at 04:31
  • @Derek朕會功夫 yes, even this doesn't work: `button.addEventListener("click", function(){var i = document.getElementsByTagName("body")[0]; i.mozRequestFullScreen();})` – Daniel Cheung Feb 09 '16 at 05:09
  • 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. – rogerdpack Oct 14 '16 at 07:30
  • 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. – Jules Bartow Jan 13 '17 at 18:59
  • Too bad Chrome does not count clicking "OK" on an alert box as a user gesture. – HolyResistance Feb 17 '21 at 11:26
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.

ᴍᴇʜᴏᴠ
  • 4,804
  • 4
  • 44
  • 57
Lukas Zech
  • 505
  • 6
  • 7
  • 2
    This has helped me *a lot*, thank you so much for sharing! – ᴍᴇʜᴏᴠ Oct 27 '15 at 18:24
  • How can I set this 'false' programmaticaly in my application? – Niraj May 04 '16 at 10:29
  • 2
    @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 [post](http://askubuntu.com/questions/313483/how-do-i-change-firefoxs-aboutconfig-from-a-shell-script) – Lukas Zech May 09 '16 at 06:00
  • @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. – Alejandro García Iglesias Mar 16 '17 at 12:34
  • @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 then – Lukas Zech Mar 17 '17 at 13:10
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>
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Sally Hammel
  • 194
  • 1
  • 8
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.

Drew
  • 1,014
  • 2
  • 10
  • 21
3

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);
})();
Bryan Sullivan
  • 318
  • 2
  • 7