update
Some checks failed
deploy / deploy (push) Has been cancelled

This commit is contained in:
toom1996
2026-08-17 20:49:25 +08:00
parent efd28d59e7
commit e83fff9a9f
6 changed files with 2067 additions and 616 deletions

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