多语言版本自动切换语言处理

This commit is contained in:
tangly1024.com
2024-04-10 18:18:20 +08:00
parent 4b5212ab4c
commit 3e93fbc061
2 changed files with 57 additions and 6 deletions

View File

@@ -6,6 +6,7 @@ import trTR from './lang/tr-TR'
import zhCN from './lang/zh-CN'
import zhHK from './lang/zh-HK'
import zhTW from './lang/zh-TW'
import { extractLangPrefix } from './utils/pageId'
/**
* 在这里配置所有支持的语言
@@ -102,3 +103,33 @@ export const loadLangFromLocalStorage = () => {
export const saveLangToLocalStorage = lang => {
localStorage.setItem('lang', lang)
}
/**
* 检测用户的预研偏好,跳转至对应的多语言网站
* @param {*} lang
* @param {*} pageId
*
*/
export const redirectUserLang = (lang, pageId) => {
if (!isBrowser) {
return
}
// 只在首页处理跳转
if (!window.location.pathname === '/') {
return
}
// const userLang = window?.navigator?.language
const userLang = 'en'
const siteIds = pageId.split(',')
// 默认是进首页; 如果检测到有一个多语言匹配了用户浏览器,则自动跳转过去
for (let index = 0; index < siteIds.length; index++) {
const siteId = siteIds[index]
const prefix = extractLangPrefix(siteId)
if (prefix === userLang) {
if (window.location.pathname.indexOf(prefix) < 0) {
window.location.href = '/' + prefix
}
}
}
}