Skip to content

Commit 1f61d01

Browse files
committed
优化i18n重定向
1 parent 9d008f2 commit 1f61d01

File tree

1 file changed

+33
-20
lines changed

1 file changed

+33
-20
lines changed

src/theme/Root/index.tsx

Lines changed: 33 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,48 +1,61 @@
1-
import React, { useEffect } from 'react';
1+
import React, { useEffect } from "react";
22

33
// 全局语言检测和重定向函数
44
function detectAndRedirectLanguage() {
5-
// 检查是否已经在英文路径下
6-
if (window.location.pathname.startsWith('/en/')) {
7-
return;
8-
}
9-
105
// 检查是否已经执行过重定向,避免无限循环
11-
if (sessionStorage.getItem('redirected')) {
6+
if (localStorage.getItem("redirected")) {
127
return;
138
}
149

10+
// 标记已执行重定向
11+
localStorage.setItem("redirected", "true");
12+
1513
// 获取用户首选语言
1614
const userLanguages = navigator.languages || [navigator.language];
17-
15+
1816
// 检查是否包含中文语言
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")
2220
);
2321

24-
// 标记已执行重定向
25-
sessionStorage.setItem('redirected', 'true');
26-
2722
// 只有非中文用户才需要重定向到英文版本
2823
// 中文用户保持在默认中文路径
2924
if (!hasChinese) {
3025
// 获取当前路径(去除开头的 /)
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(/^\//, "");
3231
const search = window.location.search;
3332
const hash = window.location.hash;
34-
33+
3534
// 构建英文版本的路径
36-
let englishPath = '/en/';
37-
if (currentPath && currentPath !== '') {
35+
let englishPath = "/en/";
36+
if (currentPath && currentPath !== "") {
3837
englishPath += currentPath;
3938
}
40-
39+
4140
// 保持查询参数和锚点
4241
const fullPath = englishPath + search + hash;
43-
42+
4443
// 跳转到英文版本
4544
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+
}
4659
}
4760
}
4861

0 commit comments

Comments
 (0)