How to redirect the user to another page?

I need to do to redirect the user to another page according to the language of the browser. For example: if the browser language english redirected to site.com/en/ .

I'm trying 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 works, but the page constantly reloads. How to solve this problem or propose another solution?

+5
source share
4 answers

The page is constantly reloading since you are not checking whether the user is on the correct language site.

On your pages, you can save a javascript variable for the server-side page language. For instance:

 var thisLanguage = 'en'; 

Then change your JavaScript logic to take this into account, and only apply redirection if the user language is different from 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; } } }); 
+4
source

I think you should discover the language by reading it from the URL, since you want to redirect users to the corresponding URL:

 $(document).ready(function () { var languageSuffix = window.location.pathname; if(languageSuffix !== '/') { return; } var userLang = navigator.language || navigator.userLanguage; switch (languageSuffix) { case '/en': window.location.href = window.location.origin + '/en'; break; case '/de': window.location.href = window.location.origin + '/de'; break; default: break; } }); 
0
source

We can check if the url matches the current url:

 $(document).ready(function () { var userLang = navigator.language || navigator.userLanguage; var urlToRedirect = ''; switch (userLang) { case 'en': urlToRedirect = window.location.origin + '/en'; break; case 'de': urlToRedirect = window.location.origin + '/de'; break; default: break; } if(urlToRedirect!=='' && urlToRedirect!==window.location.href){ window.location.href = urlToRedirect; } }); 
0
source

Try something like:

 $(document).ready(function () { var url = $(location).attr('href'); var userLang = navigator.language || navigator.userLanguage; if(url.indexOf("/en") == -1 && userLang == 'en') { window.location.href = window.location.origin + '/en'; } else if (url.indexOf("/de") == -1 && userLang == 'de'){ window.location.href = window.location.origin + '/de'; } else { // Do nothing } }); 
0
source

Source: https://habr.com/ru/post/1232959/


All Articles