I am currently using the following code to set the language on my multilingual website based on the browser’s locale
function setLanguageBasedOnBrowserLocale() {
const browserLocale = wixWindowFrontend.browserLocale;
console.log("Browser Locale:", browserLocale);
if (browserLocale === "zh-CN" || browserLocale === "zh-HK") {
wixWindowFrontend.multilingual.currentLanguage = "zh"; // Simplified Chinese
} else {
wixWindowFrontend.multilingual.currentLanguage = "en"; // English
}
}
The issue is that when I open the website from any country other than China, it correctly defaults to English. However, if I use the language switcher to manually change the language to Chinese, the website reverts back to English automatically.
Could you help me resolve this issue so that the selected language remains persistent even after it has been switched using the language switcher?
Hello,
To maintain the selected language even after it has been switched using the language switcher, you can use localStorage to store the user’s language preference. This way, you can check if a language preference has been set by the user and use that preference instead of the browser locale.
Here’s an updated version of your code:
function setLanguageBasedOnBrowserLocale() {
const storedLanguage = localStorage.getItem("userLanguage");
if (storedLanguage) {
wixWindowFrontend.multilingual.currentLanguage = storedLanguage;
} else {
const browserLocale = wixWindowFrontend.browserLocale;
console.log("Browser Locale:", browserLocale);
if (browserLocale === "zh-CN" || browserLocale === "zh-HK") {
wixWindowFrontend.multilingual.currentLanguage = "zh"; // Simplified Chinese
} else {
wixWindowFrontend.multilingual.currentLanguage = "en"; // English
}
}
}
// Call this function on page load
setLanguageBasedOnBrowserLocale();
// Add an event listener to the language switcher to store the selected language
document.querySelectorAll('.language-switcher').forEach(element => {
element.addEventListener('click', (event) => {
const selectedLanguage = event.target.dataset.language;
wixWindowFrontend.multilingual.currentLanguage = selectedLanguage;
localStorage.setItem("userLanguage", selectedLanguage);
});
});
In this code:
Check Local Storage: On page load, it first checks if there is a language preference stored in the localStorage.
Set Language: If a stored language preference is found, it sets the language based on that preference. If not, it defaults to setting the language based on the browser locale.
Store User Preference: It adds an event listener to the language switcher elements to store the selected language in localStorage whenever a user manually switches the language.
Still same result
please note that I am switching off the dashboard Auto Language, I just use the normal language selector on the webpage and I added the code on the master page