|
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/')) { |
7 | | - return; |
8 | | - } |
9 | | - |
10 | 5 | // 检查是否已经执行过重定向,避免无限循环 |
11 | | - if (sessionStorage.getItem('redirected')) { |
| 6 | + if (localStorage.getItem("redirected")) { |
12 | 7 | return; |
13 | 8 | } |
14 | 9 |
|
| 10 | + // 标记已执行重定向 |
| 11 | + localStorage.setItem("redirected", "true"); |
| 12 | + |
15 | 13 | // 获取用户首选语言 |
16 | 14 | const userLanguages = navigator.languages || [navigator.language]; |
17 | | - |
| 15 | + |
18 | 16 | // 检查是否包含中文语言 |
19 | | - const hasChinese = userLanguages.some(lang => |
20 | | - lang.toLowerCase().includes('zh') || |
21 | | - lang.toLowerCase().includes('cn') |
| 17 | + const hasChinese = userLanguages.some( |
| 18 | + (lang) => |
| 19 | + lang.toLowerCase().includes("zh") || lang.toLowerCase().includes("cn") |
22 | 20 | ); |
23 | 21 |
|
24 | | - // 标记已执行重定向 |
25 | | - sessionStorage.setItem('redirected', 'true'); |
26 | | - |
27 | 22 | // 只有非中文用户才需要重定向到英文版本 |
28 | 23 | // 中文用户保持在默认中文路径 |
29 | 24 | if (!hasChinese) { |
30 | 25 | // 获取当前路径(去除开头的 /) |
31 | | - const currentPath = window.location.pathname.replace(/^\//, ''); |
| 26 | + // 如果当前路径是英文版本,直接使用 |
| 27 | + if (window.location.pathname.startsWith("/en/")) { |
| 28 | + return; // 已经在英文版本,不需要重定向 |
| 29 | + } |
| 30 | + const currentPath = window.location.pathname.replace(/^\//, ""); |
32 | 31 | const search = window.location.search; |
33 | 32 | const hash = window.location.hash; |
34 | | - |
| 33 | + |
35 | 34 | // 构建英文版本的路径 |
36 | | - let englishPath = '/en/'; |
37 | | - if (currentPath && currentPath !== '') { |
| 35 | + let englishPath = "/en/"; |
| 36 | + if (currentPath && currentPath !== "") { |
38 | 37 | englishPath += currentPath; |
39 | 38 | } |
40 | | - |
| 39 | + |
41 | 40 | // 保持查询参数和锚点 |
42 | 41 | const fullPath = englishPath + search + hash; |
43 | | - |
| 42 | + |
44 | 43 | // 跳转到英文版本 |
45 | 44 | window.location.href = fullPath; |
| 45 | + } else { |
| 46 | + // 中文用户重定向到默认中文路径 |
| 47 | + if (window.location.pathname.startsWith("/en/")) { |
| 48 | + // 如果当前路径是英文版本,重定向到中文版本 |
| 49 | + const currentPath = window.location.pathname.replace(/^\/en\//, "/"); |
| 50 | + const search = window.location.search; |
| 51 | + const hash = window.location.hash; |
| 52 | + |
| 53 | + // 构建中文版本的路径 |
| 54 | + const chinesePath = currentPath + search + hash; |
| 55 | + |
| 56 | + // 跳转到中文版本 |
| 57 | + window.location.href = chinesePath; |
| 58 | + } |
46 | 59 | } |
47 | 60 | } |
48 | 61 |
|
|
0 commit comments