I have a function that sets a dom node into fullscreen in a React app. It works fine for Chrome, Firefox and Edge. But in Safari, I have the error:
ref.current.requestFullscreen is not a function
The code is (the error happens in openFullscreen()
):
import { useCallback, useLayoutEffect, useState } from "react";
function isLeaving() {
return (
!document["fullscreenElement"] &&
!document["webkitFullscreenElement"] &&
!document["mozFullscreenElement"] &&
!document["msFullscreenElement"]
);
}
export default function useFullscreen(
ref: React.MutableRefObject<HTMLDivElement>
): {
isFullscreen: boolean;
openFullscreen: () => void;
closeFullscreen: () => void;
} {
const [fullscreen, setFullscreen] = useState(false);
const [isFullscreenReady, setIsFullscreenReady] = useState(false);
useLayoutEffect(() => {
document.onfullscreenchange = () => {
if (isLeaving()) {
setFullscreen(false);
setIsFullscreenReady(false);
}
};
return () => (document.onfullscreenchange = undefined);
}, [fullscreen, isFullscreenReady, ref]);
const openFullscreen = useCallback(() => {
if (ref.current) {
ref.current
.requestFullscreen()
.then(() => setIsFullscreenReady(true))
.catch(() => setIsFullscreenReady(false));
}
}, [ref]);
const closeFullscreen = useCallback(() => {
document.exitFullscreen();
setFullscreen(false);
setIsFullscreenReady(false);
}, []);
return {
isFullscreen: isFullscreenReady,
openFullscreen,
closeFullscreen,
};
}
How to fix that so I can have fullscreen in every browser?
ps: it doesn’t work in Opera too, but that’s fine with me.