Files
frontend_v2/src/components/LanguageDetector.astro
toom1996 e83fff9a9f
Some checks failed
deploy / deploy (push) Has been cancelled
update
2026-08-17 20:49:25 +08:00

36 lines
1.1 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
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>