Skip to content

Instantly share code, notes, and snippets.

@Johnz86
Created February 13, 2020 14:15
Show Gist options
  • Save Johnz86/afa34e519c2f169a1bb0ddba1fe419cf to your computer and use it in GitHub Desktop.
Save Johnz86/afa34e519c2f169a1bb0ddba1fe419cf to your computer and use it in GitHub Desktop.
Example of fulllscreen functionality written in typescript, that supports multiple browsers.
interface DocumentWithFullscreen extends HTMLDocument {
mozFullScreenElement?: Element;
msFullscreenElement?: Element;
webkitFullscreenElement?: Element;
msExitFullscreen?: () => void;
mozCancelFullScreen?: () => void;
webkitExitFullscreen?: () => void;
}
export function isFullScreen(): boolean {
const doc = document as DocumentWithFullscreen;
return !!(doc.fullscreenElement ||
doc.mozFullScreenElement ||
doc.webkitFullscreenElement ||
doc.msFullscreenElement);
}
interface DocumentElementWithFullscreen extends HTMLElement {
msRequestFullscreen?: () => void;
mozRequestFullScreen?: () => void;
webkitRequestFullscreen?: () => void;
}
export function requestFullScreen(element: DocumentElementWithFullscreen) {
if (element.requestFullscreen) {
element.requestFullscreen();
} else if (element.msRequestFullscreen) {
element.msRequestFullscreen();
} else if (element.webkitRequestFullscreen) {
element.webkitRequestFullscreen();
} else if (element.mozRequestFullScreen){
element.mozRequestFullScreen();
}
}
export function exitFullScreen(doc: DocumentWithFullscreen) {
if (doc.exitFullscreen) {
doc.exitFullscreen();
} else if (doc.msExitFullscreen) {
doc.msExitFullscreen();
} else if (doc.webkitExitFullscreen) {
doc.webkitExitFullscreen();
} else if(doc.mozCancelFullScreen) {
doc.mozCancelFullScreen();
}
}
export function toogleFullScreen(): void {
if (isFullScreen()) {
requestFullScreen(document.documentElement);
}else {
exitFullScreen(document);
}
}
@mohammad-ahmadi10
Copy link

Hi bro.

HTMLDocument is deprecated.
please amend it if you have time!

@gogsh
Copy link

gogsh commented Feb 1, 2023

Here is an error in last toogleFullScreen function. Should be:

export function toogleFullScreen(): void {
    if (!isFullScreen()) { // change here
        requestFullScreen(document.documentElement);
    }else {
        exitFullScreen(document);
    }
}

@guoapeng
Copy link

image
I am using similar approach to handle fullscreen and exitFullScreen request. but it seems that in some browsers even requestFullscreen is available but inside requestFullscreen method, it may throw "fullscreen is not supported" exception as above screenshot from Sentry.
does anyone have idea on how to make the toogleFullScreen() more robust?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment