Skip to content

Commit 9a8697f

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

1 file changed

Lines changed: 18 additions & 18 deletions

File tree

src/theme/Root/index.tsx

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,46 @@
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/')) {
5+
// 检查是否已经执行过重定向,避免无限循环
6+
if (localStorage.getItem("redirected")) {
77
return;
88
}
99

10-
// 检查是否已经执行过重定向,避免无限循环
11-
if (sessionStorage.getItem('redirected')) {
10+
// 标记已执行重定向
11+
localStorage.setItem("redirected", "true");
12+
13+
// 检查是否已经在英文路径下
14+
if (window.location.pathname.startsWith("/en/")) {
1215
return;
1316
}
1417

1518
// 获取用户首选语言
1619
const userLanguages = navigator.languages || [navigator.language];
17-
20+
1821
// 检查是否包含中文语言
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")
2225
);
2326

24-
// 标记已执行重定向
25-
sessionStorage.setItem('redirected', 'true');
26-
2727
// 只有非中文用户才需要重定向到英文版本
2828
// 中文用户保持在默认中文路径
2929
if (!hasChinese) {
3030
// 获取当前路径(去除开头的 /)
31-
const currentPath = window.location.pathname.replace(/^\//, '');
31+
const currentPath = window.location.pathname.replace(/^\//, "");
3232
const search = window.location.search;
3333
const hash = window.location.hash;
34-
34+
3535
// 构建英文版本的路径
36-
let englishPath = '/en/';
37-
if (currentPath && currentPath !== '') {
36+
let englishPath = "/en/";
37+
if (currentPath && currentPath !== "") {
3838
englishPath += currentPath;
3939
}
40-
40+
4141
// 保持查询参数和锚点
4242
const fullPath = englishPath + search + hash;
43-
43+
4444
// 跳转到英文版本
4545
window.location.href = fullPath;
4646
}

0 commit comments

Comments
 (0)