|
1 | | -import React, { useEffect } from 'react'; |
| 1 | +import React, { useEffect } from "react"; |
2 | 2 |
|
3 | 3 | // 全局语言检测和重定向函数 |
4 | 4 | function detectAndRedirectLanguage() { |
5 | | - // 检查是否已经在英文路径下 |
6 | | - if (window.location.pathname.startsWith('/en/')) { |
| 5 | + // 检查是否已经执行过重定向,避免无限循环 |
| 6 | + if (localStorage.getItem("redirected")) { |
7 | 7 | return; |
8 | 8 | } |
9 | 9 |
|
10 | | - // 检查是否已经执行过重定向,避免无限循环 |
11 | | - if (sessionStorage.getItem('redirected')) { |
| 10 | + // 标记已执行重定向 |
| 11 | + localStorage.setItem("redirected", "true"); |
| 12 | + |
| 13 | + // 检查是否已经在英文路径下 |
| 14 | + if (window.location.pathname.startsWith("/en/")) { |
12 | 15 | return; |
13 | 16 | } |
14 | 17 |
|
15 | 18 | // 获取用户首选语言 |
16 | 19 | const userLanguages = navigator.languages || [navigator.language]; |
17 | | - |
| 20 | + |
18 | 21 | // 检查是否包含中文语言 |
19 | | - const hasChinese = userLanguages.some(lang => |
20 | | - lang.toLowerCase().includes('zh') || |
21 | | - lang.toLowerCase().includes('cn') |
| 22 | + const hasChinese = userLanguages.some( |
| 23 | + (lang) => |
| 24 | + lang.toLowerCase().includes("zh") || lang.toLowerCase().includes("cn") |
22 | 25 | ); |
23 | 26 |
|
24 | | - // 标记已执行重定向 |
25 | | - sessionStorage.setItem('redirected', 'true'); |
26 | | - |
27 | 27 | // 只有非中文用户才需要重定向到英文版本 |
28 | 28 | // 中文用户保持在默认中文路径 |
29 | 29 | if (!hasChinese) { |
30 | 30 | // 获取当前路径(去除开头的 /) |
31 | | - const currentPath = window.location.pathname.replace(/^\//, ''); |
| 31 | + const currentPath = window.location.pathname.replace(/^\//, ""); |
32 | 32 | const search = window.location.search; |
33 | 33 | const hash = window.location.hash; |
34 | | - |
| 34 | + |
35 | 35 | // 构建英文版本的路径 |
36 | | - let englishPath = '/en/'; |
37 | | - if (currentPath && currentPath !== '') { |
| 36 | + let englishPath = "/en/"; |
| 37 | + if (currentPath && currentPath !== "") { |
38 | 38 | englishPath += currentPath; |
39 | 39 | } |
40 | | - |
| 40 | + |
41 | 41 | // 保持查询参数和锚点 |
42 | 42 | const fullPath = englishPath + search + hash; |
43 | | - |
| 43 | + |
44 | 44 | // 跳转到英文版本 |
45 | 45 | window.location.href = fullPath; |
46 | 46 | } |
|
0 commit comments