Spaces:
Sleeping
Sleeping
Upload useSessionId.ts
Browse files
aworld/cmd/web/webui/src/hooks/useSessionId.ts
ADDED
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import { useEffect, useState } from 'react';
|
2 |
+
import { v4 as uuidv4 } from 'uuid';
|
3 |
+
|
4 |
+
export const useSessionId = () => {
|
5 |
+
const [sessionId, setSessionId] = useState<string>('');
|
6 |
+
|
7 |
+
// 从URL参数中获取session ID
|
8 |
+
const getSessionIdFromURL = (): string => {
|
9 |
+
const urlParams = new URLSearchParams(window.location.search);
|
10 |
+
return urlParams.get('session_id') || '';
|
11 |
+
};
|
12 |
+
|
13 |
+
// 更新URL参数中的session ID
|
14 |
+
const updateURLSessionId = (id: string) => {
|
15 |
+
const url = new URL(window.location.href);
|
16 |
+
url.searchParams.set('session_id', id);
|
17 |
+
window.history.replaceState({}, '', url.toString());
|
18 |
+
};
|
19 |
+
|
20 |
+
// 生成新的session ID并更新URL
|
21 |
+
const generateNewSessionId = (): string => {
|
22 |
+
const newId = uuidv4();
|
23 |
+
setSessionId(newId);
|
24 |
+
updateURLSessionId(newId);
|
25 |
+
return newId;
|
26 |
+
};
|
27 |
+
|
28 |
+
useEffect(() => {
|
29 |
+
// 初始化时检查URL中是否有session ID
|
30 |
+
const urlSessionId = getSessionIdFromURL();
|
31 |
+
|
32 |
+
if (urlSessionId) {
|
33 |
+
// 如果URL中有session ID,使用它
|
34 |
+
setSessionId(urlSessionId);
|
35 |
+
} else {
|
36 |
+
// 如果URL中没有session ID,生成一个新的
|
37 |
+
generateNewSessionId();
|
38 |
+
}
|
39 |
+
}, []);
|
40 |
+
|
41 |
+
return {
|
42 |
+
sessionId,
|
43 |
+
setSessionId,
|
44 |
+
generateNewSessionId,
|
45 |
+
updateURLSessionId,
|
46 |
+
};
|
47 |
+
};
|