Hi,
I havent found our solution on the forums yet, so I am posting it here.
We are using similar multi-language approach with automatic redirect based on the browser language setting on our website.
In our case, we have separate subfolders for EN and DE versions, where visitor in browser in german is redirected to DE version of the website. However, we ran into a problem when this german user wants to switch back to english , because the language switch button leads to the homepage again, where the user would again be automatically redirected back to the german version of the website.
We solved it by using a language variable stored in browser’s localStorage. On click on the language switcher, we set a constant to the buttons text. And when a user enters the homepage we either:
– send him to the DE page (if the const is not set or if its set to DE AND the browser is in DE)
– or do nothing. (when const is EN or browser is not in german)
All you need is 1 script on homepagehead section:
<script type="text/javascript">
var language = window.navigator.language;
const userLanguage = localStorage.getItem('language');
const isGerman = language == "de" || language == "de-AT" || language == "de-LI" || language == "de-CH" || language == "de-LU";
if(!userLanguage && isGerman){
window.location.href = "/de/home";
} else if(userLanguage == 'de' && isGerman){
window.location.href = "/de/home";
}
One script in “before /body tag” of each subpage:
<script type="text/javascript">
const languageBtn = document.getElementById('languageBtn');
function handleBtnClick() {
console.log(languageBtn.innerText)
localStorage.setItem('language', languageBtn.innerText);
}
languageBtn.addEventListener('click', handleBtnClick);
window.unload = () => {
languageBtn.removeEventListener('click', handleBtnClick);
}
</script>
and set ID “languageBtn” on the language switch button in the main menu.
Hope that helps someone.