Quellcode durchsuchen

feat: 不同tab的sessionStorage同步功能实现

cuiyalong vor 3 Jahren
Ursprung
Commit
0a56279bc8
2 geänderte Dateien mit 29 neuen und 0 gelöschten Zeilen
  1. 28 0
      src/utils/functions/syncSessionStorage.js
  2. 1 0
      src/utils/index.js

+ 28 - 0
src/utils/functions/syncSessionStorage.js

@@ -0,0 +1,28 @@
+const syncKey = 'syncSessionStorage'
+const sessKey = 'sessionStorage'
+// 实时同步 sessionStorage 的 key
+const syncKeyList = ['visited-path-list']
+
+// 新打开一个tab标签页并通知其他标签页同步sessionStorage的数据到本标签页
+if (!sessionStorage.length) {
+  // 这个调用能触发storage事件,从而达到共享数据的目的
+  localStorage.setItem(syncKey, Date.now())
+}
+
+window.addEventListener('storage', function (e) {
+  if (e.key === syncKey) {
+    // 已存在的标签页会收到这个事件
+    localStorage.setItem(sessKey, JSON.stringify(sessionStorage))
+    localStorage.removeItem(sessKey)
+  } else if (e.key === sessKey && !sessionStorage.length) {
+    // 新开启的标签页会收到这个事件
+    const data = JSON.parse(e.newValue)
+    for (const k in data) {
+      sessionStorage.setItem(k, data[k])
+    }
+  } else if (syncKeyList.indexOf(e.key) !== -1) {
+    if (e.newValue) {
+      sessionStorage.setItem(e.key, e.newValue)
+    }
+  }
+})

+ 1 - 0
src/utils/index.js

@@ -1,4 +1,5 @@
 import './globalDirectives'
 import './globalFilters'
+import './functions/syncSessionStorage'
 
 export * from './globalFunctions'