Skip to content

Instantly share code, notes, and snippets.

@technikhil314
Created April 26, 2021 08:07
Show Gist options
  • Save technikhil314/7dba95d1f9a6767b1c05070e7063764e to your computer and use it in GitHub Desktop.
Save technikhil314/7dba95d1f9a6767b1c05070e7063764e to your computer and use it in GitHub Desktop.
use-page-visibility react hook
import { useEffect, useRef } from "react";
import usePageVisibility from "./usePageVisibility";
export default function App() {
const isPageVisible = usePageVisibility();
const videoRef = useRef();
useEffect(() => {
videoRef.current.muted = false;
}, []);
useEffect(() => {
const functionName = isPageVisible ? "play" : "pause";
videoRef.current[functionName]();
}, [isPageVisible]);
return (
<div className="App">
<video
ref={videoRef}
src="https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-mp4-file.mp4"
autoplay
muted
height="200"
width="300"
id="video"
controls
loop
></video>
</div>
);
}
import { useEffect, useState } from "react";
export default function usePageVisibility() {
const [isVisible, setIsVisible] = useState(true);
useEffect(() => {
let hidden, visibilityChange;
if (typeof document.hidden !== "undefined") {
// Opera 12.10 and Firefox 18 and later support
hidden = "hidden";
visibilityChange = "visibilitychange";
} else if (typeof document.msHidden !== "undefined") {
hidden = "msHidden";
visibilityChange = "msvisibilitychange";
} else if (typeof document.webkitHidden !== "undefined") {
hidden = "webkitHidden";
visibilityChange = "webkitvisibilitychange";
}
const handleVisibilityChange = (e) => {
e.stopPropagation();
if (document[hidden]) {
setIsVisible(false);
} else {
setIsVisible(true);
}
};
window.onblur = (e) => {
setIsVisible(false);
};
window.onfocus = (e) => {
setIsVisible(true);
};
document.addEventListener(visibilityChange, handleVisibilityChange, true);
return () => {
document.removeEventListener(visibilityChange, handleVisibilityChange);
};
}, []);
return isVisible;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment