1

I have a french and an english version of my website:
*example.com/ is my english version.
*example.com/fr/ is my french version.

So they have the possibility to change the websites version by clicking on a flag,but by default if they arrive on example.com it will be in english.

I would like to give them the version corresponding to their language preference, i detect language preference with :

var language = window.navigator.userLanguage || window.navigator.language;

But then what code do i use so that when they arrive on the webpage, it will give the version according to the user language preference ?

And if the website gives a french version but the user wants english version, still has the possiblity to change manualy.

Jackymamouth
  • 159
  • 2
  • 11

1 Answers1

1

You'll have to redirect them:

if (window.navigator.language === 'fr') {
    window.location.href = "http://example.com/fr/";
}

Please keep in mind that the window.navigator.language property is implemented differently across browsers and you may have to find your preferred language in an array (like window.navigator.languages).

A better option would be to check the Accept-Language header on the HTTP request on the server side, and redirect accordingly on the server side.

There are also JavaScript-based internationalization methods, but they don't normally involve redirecting the site.

Community
  • 1
  • 1
KWeiss
  • 2,954
  • 3
  • 21
  • 37
  • But the problem here is that if javascript puts the website to french version because window.navigator.language == "fr" but the user wants to use english version, and lets say he puts it to english manually Then when he will return on the main page or any page with that javascript code, it will be put back to french . – Jackymamouth Apr 26 '16 at 07:38
  • In that case, you can add an additional JavaScript parameter like `wants_english = true` and check for that in the if statement as well. This will have to be done server side, so you might as well use a GET parameter and do the entire redirect on the server. If you absolutely want to do it client side, make a `localStorage` entry in the user's browser when he chooses his language. Keep in mind that this is much more fragile than a server side solution, because a user might block JavaScript or LocalStorage. – KWeiss Apr 26 '16 at 07:41