Parcourir la source

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

Xwite il y a 3 ans
Parent
commit
028f840668

+ 0 - 1
modules/web/src/components/ChapterContent.vue

@@ -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
   );

+ 18 - 9
modules/web/src/views/BookChapter.vue

@@ -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();