aw-bubakik aw-bubakik - 4 months ago 20x
Javascript Question

javascript - Full screen

if (!document.fullscreenElement
&& !document.mozFullScreenElement
&& !document.webkitFullscreenElement
&& !document.msFullscreenElement) {

if (document.documentElement.requestFullscreen) {
} else if (document.documentElement.msRequestFullscreen) {
} else if (document.documentElement.mozRequestFullScreen) {
} else if (document.documentElement.webkitRequestFullscreen) {
else {
if (document.exitFullscreen) {
} else if (document.msExitFullscreen) {
} else if (document.mozCancelFullScreen) {
} else if (document.webkitExitFullscreen) {

I have this code for toggling full screen. It works, but it has some little issues.

  1. When I'm clicking to the full screen button, after refresh full screen mode exits, but if I press F11 and refresh, full screen won't exit.

  2. If full screen mode is enabled, after pressing F11, clicking on full screen button, will not work

How Can I fixed this problems?


I don't know if you'll be able to fix those issues. They happen because there are two different full screen modes:

  • One applied to elements/documents that you trigger using JavaScript (the one you are using with the API). This fullscreen is lost when the page reloads or when you browse to a different page.
  • Another native to the browser that is set by the user with F11 (applied to the browser itself, and not to the page/document: if you reload or browse to a different site, the browser will continue in fullscreen mode).

While you can control the first one with JS, you cannot control the other. This makes sense from a usability/security point of view: you should be able to control the behavior within your page, but not outside of it or the user's preferences.

The issues that you are facing happen because:

  • Issue 1:
    • By default the fullscreen flag is unset. When you go to full screen mode with the API, you are setting that flag, but when you refresh the page, the flag goes to its original value (unset) and the full screen is lost. The same way that any other JavaScript variable would be reset when reloading a page.
    • If you set the browser on fullscreen mode (using F11), it will remain that way until you exit the fullscreen, independently of where you browse or even if you close the browser. You are setting a browser's preference.
  • Issue 2:
    • Actually, this is not an issue as it works as expected. The problem is that you are going fullscreen (element) within a fullscreen (window) (fullscreenception! :P). So you don't see any apparent change, but there really is a change as the fullscreen flag is set. You can see the difference in this demo by Robert Nyman. He has added CSS so the page will go red when on :fullscreen. Press F11 and notice how the background doesn't turn red, now click the "Fullscreen/Cancel fullscreen" buttons to see how the background color changes.