简体   繁体   中英

How can we programmatically enter and exit the fullscreen mode in javascript?

Here's documentation on exiting fullscreen mode.

I used this code that I learnd to make the browser go fullscreen (it works), but my attempts to modify a version of it to exit fullscreen failed. Dealing with these non-standard APIs is a little tricky, with each browser implementing it a bit differently.

Here's the code:

// Bring the page into full-screen mode - Works!
function requestFullScreen(element) {

    // Supports most browsers and their versions.
    var requestMethod = element.requestFullScreen || 
        element.webkitRequestFullScreen           || 
        element.mozRequestFullScreen              || 
        element.msRequestFullScreen;
    if (requestMethod) {
        requestMethod.call(element);
    } else if ( typeof window.ActiveXObject !== "undefined") {
        var wscript = new ActiveXObject("WScript.Shell");
        if (wscript !== null) {
            wscript.SendKeys("{F11}");
        }
    }
}

// Exit fullscreen - Doesn't work!
function exitFullScreen(element){
    var requestMethod = element.exitFullscreen || 
        element.mozCancelFullScreen            || 
        element.webkitExitFullscreen           || 
        element.msExitFullscreen;
    if (requestMethod) {
        requestMethod();
    } else {
        console.log("Oops. Request method false.");
    }
}

And the calls:

var $fullscreenButton = $("#fullscreen-button");
var $smallscreenButton = $("#smallscreen-button");

$fullscreenButton.on("click", function() {
    var elem = document.body;

    // Make the body go full screen.
    requestFullScreen(elem);
});

$smallscreenButton.on("click", function() {
    var elem = document.body;

    // Exit full screen.
    exitFullScreen(elem);
});

What's wrong with the exitFullScreen function? How can I fix it?

Edit:

  • I'm working on a JSFiddle for this!
  • By "Doesn't work", I meant that it outputs "Oops. Request method false."
  • I'm calling the function exitFullScreen() with the parameter document.body

JSFiddle:

While the full screen request function works for me in the browser normally, I could not get it to work in JSFiddle , and I'm unsure whether this is because of my own mistake, or something to do with JSFiddle.

For entering the fullscreen there were some issues with the capitalization.

For the exiting you need to call it on the document and not on the body , and you also need to apply it correctly instead of calling the reference to the method..

so requestMethod.call(element); for exiting as well.

See demo at http://jsfiddle.net/gaby/FGX72/show
( tested on latest IE/Chrome/FireFox )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM