blog

December 23, 2018

jQuery - user language detection.

keywords:

This may come in handy:

    You can determine the user language by using both navigator.language and navigator.userLanguage properties. In theory it should be pretty simple, because the only thing You need is to define a variable and then to use it in a classic if-based condition - something like that:

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

    if (userLang === "pl") {
    ...
    }

    In practice, however, You may discover some surprising things, like:

    Some language tags may sometimes take a different forms.
    This is a pretty strange issue. Let's say You use Polish as Your default language in Chrome from the very beginning. If You enter navigator.language into the console as a result You will receive "pl-PL". But if You change the language in Chrome settings and after a while set it back to the Polish - although You might expect the return to "pl-PL" mentioned above - it is not the case (!): it will show You a sole "pl".

    So now, although the script use both navigator.language and navigator.userLanguage ascribed as a variable - the console responses only to one of them: navigator.language. And if - as in case of Polish - Your language tag may vary depending on changing settings, Your script could not work, being based only on one language tag variant. To make it work in any circumstances You need to consider both variants by adding an extra if statement.


    During various tests of Your language detecting script in action Chrome may give You yet another surprise. Let's say Your native language is other than English, but You need to test Your website behavior in English Chrome. It seems easy to change the UI language in this web-browser settings - as a result You might naturally expect of reflection of this change rendered by the website. Strangely enough it doesn't happen - Your website still will be indicating that You use Your native language (!), although You've noticed the change in the Chrome UI. The thing is that for new language to be considered by the console (= jQuery code) - it must be placed on the very beginning of the language list. Only then Your website may "notice" the change and act accordingly.

    Actually when it comes to UI language - to observe any change in a website behavior You don't need to change it every single time - You only need to place Your preferred language on top of the list in Chrome settings ;) .

    No comments:

    Post a Comment