ZaiZai 7 mesiacov pred
rodič
commit
4357af438f
2 zmenil súbory, kde vykonal 25 pridanie a 12 odobranie
  1. 1 1
      public/version.json
  2. 24 11
      src/plugins/HcSocket.js

+ 1 - 1
public/version.json

@@ -1,3 +1,3 @@
 {
-  "value": "20240717094632"
+  "value": "20240717120150"
 }

+ 24 - 11
src/plugins/HcSocket.js

@@ -4,34 +4,39 @@ import { getObjValue, isNullES } from 'js-fast-way'
 // 长链接推送插件
 class HcSocket {
 
-    limit = 30
-    interval = 1000
-
     constructor(data, change) {
+        this.limit = 30
+        this.interval = 1000
         this.param = getObjValue(data)
         this.onChange = change
         this.socket = null
         this.create()
+        this.moreTabs()
     }
 
     //创建连接
     create() {
         const { projectId, contractId, userId } = this.param
         const { socket: socketUrl, clientId } = website
+
         if (isNullES(socketUrl) || isNullES(clientId) || isNullES(projectId) || isNullES(contractId) || isNullES(userId)) {
             return
         }
+
         //拼接URL并登录socket
         const url = `${socketUrl}/${clientId}/${projectId}/${contractId}/${userId}`
         this.socket = new WebSocket(url)
-        this.socket.onopen = function () {
+
+        this.socket.onopen = ()=> {
             console.log('WebSocket 链接成功')
         }
-        this.socket.onclose = function () {
+
+        this.socket.onclose = async () => {
             console.log('WebSocket 链接已断开')
-            this.reconnect()
+            await this.reconnect()
         }
-        this.socket.onmessage = function ({ data }) {
+
+        this.socket.onmessage = ({ data })=> {
             console.log(data)
             try {
                 const parsedData = JSON.parse(data)
@@ -42,9 +47,6 @@ class HcSocket {
                 console.error('解析 WebSocket 数据时出错:', error)
             }
         }
-        this.socket.onerror = function ({ data }) {
-            console.log('WebSocket 发生错误:', data)
-        }
     }
 
     //发送消息
@@ -66,10 +68,21 @@ class HcSocket {
         }
         await new Promise(resolve => setTimeout(resolve, this.interval))
         if (!this.isSocket()) {
-            this.reconnect(attempts + 1)
+            await this.reconnect(attempts + 1)
         }
     }
 
+    // 处理多标签页问题
+    moreTabs() {
+        document.addEventListener('visibilitychange', () => {
+            if (document.visibilityState === 'visible' && !this.isSocket()) {
+                this.create()
+            } else if (document.visibilityState === 'hidden') {
+                this.close()
+            }
+        })
+    }
+
     //关闭或断开连接
     close() {
         if (!this.isSocket()) return