[skip ci] web: VisibilityChange兼容Safari 14 14.5

This commit is contained in:
Xwite
2023-05-12 21:51:54 +08:00
parent 114b70c317
commit de516f8983
2 changed files with 18 additions and 10 deletions

View File

@@ -58,7 +58,6 @@ const titleRef = ref();
const paragraphRef = ref();
const scrollToReadedLength = (length) => {
if (length === 0) return;
console.log("已读长度", length);
let paragraphIndex = chapterPos.value.findIndex(
(wordCount) => wordCount >= length
);

View File

@@ -324,15 +324,18 @@ const saveReadingBookProgressToBrowser = (index, pos) => {
// 进度同步
// 返回同步 同步请求会在获取书架前完成
// 刷新 关闭页面
const syncBookProgress = () => {
console.log("page hide");
// 刷新 关闭页面 切换tab 返回桌面 等操作 https://developer.mozilla.org/zh-CN/docs/Web/API/Document/visibilitychange_event
const onVisibilityChange = () => {
if (!bookProgress.value) return;
// 常规请求可能会被取消 使用Fetch keep-alive 或者 navigator.sendBeacon
navigator.sendBeacon(
`${import.meta.env.VITE_API || location.origin}/saveBookProgress`,
JSON.stringify(bookProgress.value)
if (document.visibilityState == 'hidden') {
// Safari > 14 和 非Safari移除额外pagehide event
document.removeEventListener("pagehide", onVisibilityChange);
// 常规请求可能会被取消 使用Fetch keep-alive 或者 navigator.sendBeacon
navigator.sendBeacon(
`${import.meta.env.VITE_API || location.origin}/saveBookProgress`,
JSON.stringify(bookProgress.value)
);
}
};
// 定时同步
@@ -478,7 +481,10 @@ onMounted(() => {
getContent(chapterIndex, true, chapterPos);
window.addEventListener("keyup", handleKeyPress);
window.addEventListener("visibilitychange", syncBookProgress);
// 兼容Safari < 14
document.addEventListener("visibilitychange", onVisibilityChange);
// 兼容Safari < 14.5
document.addEventListener("pagehide", onVisibilityChange);
//监听底部加载
scrollObserve.value = new IntersectionObserver(handleIScrollObserve, {
rootMargin: "-100% 0% 20% 0%",
@@ -498,7 +504,10 @@ onMounted(() => {
onUnmounted(() => {
window.removeEventListener("keyup", handleKeyPress);
window.removeEventListener("visibilitychange", syncBookProgress);
// 兼容Safari < 14
document.removeEventListener("visibilitychange", onVisibilityChange);
// 兼容Safari < 14.5
document.removeEventListener("pagehide", onVisibilityChange);
readSettingsVisible.value = false;
popCataVisible.value = false;
scrollObserve.value?.disconnect();