Skip to content

Commit 3eaa895

Browse files
committed
feat: implement language detection for Chinese users
1 parent 0e698e9 commit 3eaa895

3 files changed

Lines changed: 48 additions & 3 deletions

File tree

docusaurus.config.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ const config = {
1515
botId: process.env.BOT_ID,
1616
patToken: process.env.TOKEN
1717
},
18+
// Add client module for language detection
19+
clientModules: [require.resolve('./src/clientModules/lang-redirect.js')],
1820
markdown: {
1921
hooks: {
2022
onBrokenMarkdownLinks: 'warn',

src/clientModules/lang-redirect.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* Docusaurus Client Module for Language Detection
3+
* This module runs on the client side and handles browser language detection
4+
*/
5+
export function onRouteDidUpdate({ location, previousLocation }) {
6+
// Only run on root path
7+
if (location.pathname !== '/' && location.pathname !== '/index.html') {
8+
return;
9+
}
10+
11+
// Check if user has an existing locale preference (manual language selection)
12+
const savedLocale = localStorage.getItem('docusaurus.locale');
13+
if (savedLocale === 'en') {
14+
// User explicitly chose English, respect it and don't redirect
15+
return;
16+
}
17+
18+
if (savedLocale === 'zh-CN') {
19+
// User chose Chinese, no need to redirect
20+
return;
21+
}
22+
23+
// Check if this is the first visit to the root path in this session
24+
if (sessionStorage.getItem('clientLangDetectionDone')) {
25+
return;
26+
}
27+
28+
// Detect browser language
29+
const browserLang = navigator.language || navigator.userLanguage || '';
30+
31+
// Redirect Chinese users to Chinese version
32+
if (browserLang.toLowerCase().startsWith('zh')) {
33+
// Mark as done before redirecting to prevent loops
34+
sessionStorage.setItem('clientLangDetectionDone', '1');
35+
// Redirect Chinese users to Chinese version
36+
window.location.replace('/zh-CN/');
37+
} else {
38+
// Mark as done for non-Chinese users too
39+
sessionStorage.setItem('clientLangDetectionDone', '1');
40+
}
41+
}

static/_redirects

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
# Redirect users from China to chinese version at /zh-CN.
2-
/ /zh-cn 302! Country=cn
3-
# Also users with Chinese language should be redirected to /zh-cn
4-
# / /zh-cn 302! Language=zh
2+
# Disabled - relying on client-side browser language detection instead
3+
# The ! flag causes forced redirects that prevent manual language switching
4+
# / /zh-CN 302 Country=cn
5+
# Also users with Chinese language should be redirected to /zh-CN
6+
# / /zh-CN 302 Language=zh

0 commit comments

Comments
 (0)