Skip to content

Commit e3eb002

Browse files
committed
fix:(useChatStore) 修复同一域名下的多个 iframe 共享相同的 sessionStorage 和 localStorage,这可能导致状态混乱
1 parent bd93f28 commit e3eb002

File tree

1 file changed

+19
-6
lines changed

1 file changed

+19
-6
lines changed

projects/app/src/web/core/chat/context/useChatStore.ts

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,13 +23,25 @@ type State = {
2323
const createCustomStorage = () => {
2424
const sessionKeys = ['source', 'chatId', 'appId'];
2525

26+
// 从 URL 中获取 appId 作为存储键的一部分
27+
const getStorageKey = (name: string) => {
28+
let appId = '';
29+
if (typeof window !== 'undefined') {
30+
const urlParams = new URLSearchParams(window.location.search);
31+
appId = urlParams.get('appId') || '';
32+
}
33+
return appId ? `${name}_${appId}` : name;
34+
};
35+
2636
return {
2737
getItem: (name: string) => {
28-
const sessionData = JSON.parse(sessionStorage.getItem(name) || '{}');
29-
const localData = JSON.parse(localStorage.getItem(name) || '{}');
38+
const storageKey = getStorageKey(name);
39+
const sessionData = JSON.parse(sessionStorage.getItem(storageKey) || '{}');
40+
const localData = JSON.parse(localStorage.getItem(storageKey) || '{}');
3041
return JSON.stringify({ ...localData, ...sessionData });
3142
},
3243
setItem: (name: string, value: string) => {
44+
const storageKey = getStorageKey(name);
3345
const data = JSON.parse(value);
3446

3547
// 分离 session 和 local 数据
@@ -42,15 +54,16 @@ const createCustomStorage = () => {
4254

4355
// 分别存储
4456
if (Object.keys(sessionData).length > 0) {
45-
sessionStorage.setItem(name, JSON.stringify({ state: sessionData, version: 0 }));
57+
sessionStorage.setItem(storageKey, JSON.stringify({ state: sessionData, version: 0 }));
4658
}
4759
if (Object.keys(localData).length > 0) {
48-
localStorage.setItem(name, JSON.stringify({ state: localData, version: 0 }));
60+
localStorage.setItem(storageKey, JSON.stringify({ state: localData, version: 0 }));
4961
}
5062
},
5163
removeItem: (name: string) => {
52-
sessionStorage.removeItem(name);
53-
localStorage.removeItem(name);
64+
const storageKey = getStorageKey(name);
65+
sessionStorage.removeItem(storageKey);
66+
localStorage.removeItem(storageKey);
5467
}
5568
};
5669
};

0 commit comments

Comments
 (0)