fix: emb page cannot save lng;feat: Add classify error log (#3367)

* fix: emb page cannot save lng

* perf: i18n check
This commit is contained in:
Archer
2024-12-11 14:18:48 +08:00
committed by GitHub
parent 096afef629
commit 048f5a2d53
2 changed files with 30 additions and 17 deletions

View File

@@ -1,15 +1,27 @@
import Cookies, { CookieAttributes } from 'js-cookie';
import Cookies from 'js-cookie';
import { useTranslation } from 'next-i18next';
import { LangEnum } from '../../../projects/app/src/web/common/utils/i18n';
const setCookie = (key: string, value: string, options?: CookieAttributes) => {
Cookies.set(key, value, options);
};
const getCookie = (key: string) => {
return Cookies.get(key);
};
const LANG_KEY = 'NEXT_LOCALE';
const isInIframe = () => {
try {
return window.self !== window.top;
} catch (e) {
return true;
}
};
const setLang = (value: string) => {
if (isInIframe()) {
localStorage.setItem(LANG_KEY, value);
} else {
// 不在 iframe 中,同时使用 Cookie 和 localStorage
Cookies.set(LANG_KEY, value, { expires: 30 });
localStorage.setItem(LANG_KEY, value);
}
};
const getLang = () => {
return localStorage.getItem(LANG_KEY) || Cookies.get(LANG_KEY);
};
export const useI18nLng = () => {
const { i18n } = useTranslation();
@@ -26,23 +38,19 @@ export const useI18nLng = () => {
const onChangeLng = async (lng: string) => {
const lang = languageMap[lng] || 'en';
const prevLang = getLang();
setCookie(LANG_KEY, lang, {
expires: 30
});
const currentLng = i18n?.language;
if (!currentLng) return;
setLang(lang);
await i18n?.changeLanguage?.(lang);
if (currentLng !== lang) {
if (prevLang && prevLang !== lang) {
window?.location?.reload?.();
}
};
const setUserDefaultLng = () => {
if (!navigator || !localStorage) return;
if (getCookie(LANG_KEY)) return onChangeLng(getCookie(LANG_KEY) as string);
if (getLang()) return onChangeLng(getLang() as string);
const lang = languageMap[navigator.language] || 'en';