()
| 1 | export default function detectLanguage() { |
| 2 | // 获取浏览器语言 |
| 3 | const userLang = navigator.language || navigator.userLanguage; |
| 4 | console.log('Browser language detected:', userLang); // 调试输出 |
| 5 | |
| 6 | // 支持的语言列表 |
| 7 | const supportedLanguages = ['en', 'zh']; |
| 8 | |
| 9 | // 默认语言 |
| 10 | const defaultLanguage = 'en'; |
| 11 | |
| 12 | // 检查语言是否支持,并获取对应的语言代码 |
| 13 | const languagePrefix = userLang.slice(0, 2); // 获取前两位字符 |
| 14 | console.log('Language prefix:', languagePrefix); // 调试输出 |
| 15 | |
| 16 | const selectedLanguage = supportedLanguages.includes(languagePrefix) |
| 17 | ? (languagePrefix === 'zh' ? 'zh-Hans' : languagePrefix) |
| 18 | : defaultLanguage; |
| 19 | |
| 20 | console.log('Selected language:', selectedLanguage); // 调试输出 |
| 21 | |
| 22 | // 如果当前语言不是用户的浏览器语言,进行重定向 |
| 23 | if (selectedLanguage !== document.documentElement.lang) { |
| 24 | const basePath = window.location.pathname.split('/')[1]; |
| 25 | const newPath = `/${selectedLanguage}/${window.location.pathname.split('/').slice(2).join('/')}`; |
| 26 | console.log('Redirecting to:', newPath); // 调试输出 |
| 27 | window.location.replace(newPath); |
| 28 | } |
| 29 | } |
nothing calls this directly
no outgoing calls
no test coverage detected