Skip to content

Instantly share code, notes, and snippets.

@DesignHhuang
Created September 28, 2023 10:48
Show Gist options
  • Save DesignHhuang/8063d89829bfef47acfbca66398eecba to your computer and use it in GitHub Desktop.
Save DesignHhuang/8063d89829bfef47acfbca66398eecba to your computer and use it in GitHub Desktop.
usePageVisibility :使用页面可见性
import { onMounted, onUnmounted } from 'vue';
export const usePageVisibility = (callback = () => { }) => {
let hidden, visibilityChange;
if (typeof document.hidden !== "undefined") {
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 = () => {
callback(document[hidden]);
}
onMounted(() => {
document.addEventListener(visibilityChange, handleVisibilityChange, false);
});
onUnmounted(() => {
document.removeEventListener(visibilityChange, handleVisibilityChange);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment