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

This commit is contained in:
Xwite
2023-05-12 21:52:43 +08:00
parent 114b70c317
commit de516f8983
2 changed files with 18 additions and 10 deletions
@@ -58,7 +58,6 @@ const titleRef = ref();
const paragraphRef = ref(); const paragraphRef = ref();
const scrollToReadedLength = (length) => { const scrollToReadedLength = (length) => {
if (length === 0) return; if (length === 0) return;
console.log("已读长度", length);
let paragraphIndex = chapterPos.value.findIndex( let paragraphIndex = chapterPos.value.findIndex(
(wordCount) => wordCount >= length (wordCount) => wordCount >= length
); );
+18 -9
View File
@@ -324,15 +324,18 @@ const saveReadingBookProgressToBrowser = (index, pos) => {
// 进度同步 // 进度同步
// 返回同步 同步请求会在获取书架前完成 // 返回同步 同步请求会在获取书架前完成
// 刷新 关闭页面 // 刷新 关闭页面 切换tab 返回桌面 等操作 https://developer.mozilla.org/zh-CN/docs/Web/API/Document/visibilitychange_event
const syncBookProgress = () => { const onVisibilityChange = () => {
console.log("page hide");
if (!bookProgress.value) return; if (!bookProgress.value) return;
// 常规请求可能会被取消 使用Fetch keep-alive 或者 navigator.sendBeacon if (document.visibilityState == 'hidden') {
navigator.sendBeacon( // Safari > 14 和 非Safari移除额外pagehide event
`${import.meta.env.VITE_API || location.origin}/saveBookProgress`, document.removeEventListener("pagehide", onVisibilityChange);
JSON.stringify(bookProgress.value) // 常规请求可能会被取消 使用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); getContent(chapterIndex, true, chapterPos);
window.addEventListener("keyup", handleKeyPress); 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, { scrollObserve.value = new IntersectionObserver(handleIScrollObserve, {
rootMargin: "-100% 0% 20% 0%", rootMargin: "-100% 0% 20% 0%",
@@ -498,7 +504,10 @@ onMounted(() => {
onUnmounted(() => { onUnmounted(() => {
window.removeEventListener("keyup", handleKeyPress); window.removeEventListener("keyup", handleKeyPress);
window.removeEventListener("visibilitychange", syncBookProgress); // 兼容Safari < 14
document.removeEventListener("visibilitychange", onVisibilityChange);
// 兼容Safari < 14.5
document.removeEventListener("pagehide", onVisibilityChange);
readSettingsVisible.value = false; readSettingsVisible.value = false;
popCataVisible.value = false; popCataVisible.value = false;
scrollObserve.value?.disconnect(); scrollObserve.value?.disconnect();