36
src/components/LanguageDetector.astro
Normal file
36
src/components/LanguageDetector.astro
Normal file
@ -0,0 +1,36 @@
|
||||
---
|
||||
import { pathHasLocale, getRelativeLocaleUrl } from 'astro:i18n';
|
||||
|
||||
// 使用 pathHasLocale 安全判断当前路径是否已包含任何语言前缀(返回 boolean)
|
||||
const hasLocale = pathHasLocale(Astro.url.pathname);
|
||||
|
||||
// 自动生成中文根路径
|
||||
const cnRootUrl = getRelativeLocaleUrl('cn', '');
|
||||
---
|
||||
|
||||
<script is:inline define:vars={{ hasLocale, cnRootUrl }}>
|
||||
(() => {
|
||||
try {
|
||||
// 当前路径已带有语言前缀(如 /cn/ 或 /en/),直接跳过
|
||||
if (hasLocale) return;
|
||||
|
||||
// 避免重复跳转
|
||||
if (sessionStorage.getItem('lang-redirect')) return;
|
||||
|
||||
// 判定浏览器偏好语言
|
||||
const langs = navigator.languages || [navigator.language || 'en'];
|
||||
const isZh = langs.some((l) => l.toLowerCase().startsWith('zh'));
|
||||
|
||||
if (!isZh) return;
|
||||
|
||||
sessionStorage.setItem('lang-redirect', '1');
|
||||
|
||||
// 拼接真实跳转路径
|
||||
const { pathname, search, hash } = location;
|
||||
const cleanPath = pathname === '/' ? '' : pathname;
|
||||
const targetUrl = `${cnRootUrl}${cleanPath.replace(/^\//, '')}${search}${hash}`;
|
||||
|
||||
location.replace(targetUrl);
|
||||
} catch (e) {}
|
||||
})();
|
||||
</script>
|
||||
Reference in New Issue
Block a user