sindresorhus / screenfull

Simple wrapper for cross-browser usage of the JavaScript Fullscreen API
https://sindresorhus.com/screenfull
MIT License
7.08k stars 698 forks source link

Detect when exiting fullscreen is triggered by ESC key press #179

Open matcho opened 4 years ago

matcho commented 4 years ago

Hello,

When binding a function to "change" event, through .on() method, how is it possible to detect either :

I couldn't find such information in the event object.

What I'm trying to achieve is to detect when the browser is exiting fullscreen mode because ESC key was pressed.

Thanks for any help, screenfull is great, Mathias

sindresorhus commented 4 years ago

whether this change event was triggered by pressing ESC key

I don't think browsers expose this information at all.

whether the browser is entering or exiting fullscreen mode

This could possibly be added.

h3rb commented 3 years ago

perhaps you can test for the ESC key

(window.addEventListener( "onkeyup", ... )

there is also https://stackoverflow.com/questions/10706070/how-to-detect-when-a-page-exits-fullscreen

chenxiaoyao6228 commented 3 years ago

any workarounds ?

Dhruvinhp commented 2 years ago

// you can use it like this, const escFunction = useCallback((event) => { if (event.keyCode === 27) { console.log("----logic----") } }, []); useEffect(() => { document.addEventListener("keydown", escFunction); }, []);

// And don't forget to import useCallback from react, hope this helps ;)

surdu commented 2 years ago

whether the browser is entering or exiting fullscreen mode

const isFullscreen = !!document.fullscreenElement;

You could use this inside your change handler.

gurvirbaraich commented 1 year ago

You could check for ESC key within your change handler

class FullScreenExitHandler {
    static ESCKeyPressed = false;

    onFullScreenChange = () => {
        /** Full Screen Change Logic */

    if (FullScreenExitHandler.ESCKeyPressed) {
        /** ESC Key Pressed was used to exit fullscreen */
    }

    /** Setting ESC key staus to default */
        FullScreenExitHandler.ESCKeyPressed = false;
    };
}

/** Checks for keypresses on the dom */
window.addEventListener("keydown", function (event) {
    if (event.keyCode === 27) {
    FullScreenExitHandler.ESCKeyPressed = true;
    }
});
DM390 commented 2 months ago

if (document.addEventListener) { document.addEventListener('fullscreenchange', exitHandler, false); document.addEventListener('mozfullscreenchange', exitHandler, false); document.addEventListener('MSFullscreenChange', exitHandler, false); document.addEventListener('webkitfullscreenchange', exitHandler, false); }

const exitHandler = () => { if (!document.webkitIsFullScreen && !document.mozFullScreen && !document.msFullscreenElement) { // Run code on exit } }