I need to make to redirect the user to another page, in accordance to the language of the browser. For example: if the language of the browser english
redirect to site.com/en/
.
I try to do like this:
$(document).ready(function () {
var userLang = navigator.language || navigator.userLanguage;
switch (userLang) {
case 'en':
window.location.href = window.location.origin + '/en';
break;
case 'de':
window.location.href = window.location.origin + '/de';
break;
default:
break;
}
});
It's works but the page is constantly reloaded. How to solve it or prompt another solution?
The page is constantly reloaded as you're not checking whether the user is already on the correct language site.
On your pages you could store a javascript variable for the pages language produced server-side. For example:
var thisLanguage = 'en';
Then change your javascript logic to take this into account and only apply the redirect if the user's language is different to thisLanguage
:
$(document).ready(function () {
var userLang = navigator.language || navigator.userLanguage;
if (userLang != thisLanguage){
switch (userLang) {
case 'en':
window.location.href = window.location.origin + '/en';
break;
case 'de':
window.location.href = window.location.origin + '/de';
break;
default:
break;
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With