How to: Client-side language detection

Posted . Visible to the public.

When you have a localized website, you may want to redirect users to their preferred language when they visit the root path.
Here is how to do it without a server-side component (like a Rails application).

  • Use JavaScript's navigator.language (real browsers and IE11+) and navigator.userLanguage (old IEs).
  • Use a <meta> refresh as fallback
  • Provide buttons for paranoid users that disabled JavaScript and meta refreshs.

JavaScript

The following JavaScript will try to auto-detect a user's preferred language.

It understands strings like like de_AT, and if the user prefers neither of your supported languages it redirects them to a default.

window.location.href = (function() {
  var languageString = navigator.language || navigator.userLanguage || '';
  var language = languageString.split(/[_-]/)[0]).toLowerCase();

  switch (language) {
    case 'de':
      return "/de/";
    case 'en':
      return "/en/";
    default:
      return "/en/";
  }
})();

Note that old IEs support only navigator.userLanguage which returns the regional setting of the operating system.

Fallback

For users without JavaScript, you may want to redirect them to your default locale. Do that by adding a meta refresh tag to your page:

<meta content="0; URL='/en/'" http-equiv="refresh">

A few users around the interwebs will also disable that. You may want to add some links to your page that such users can use:

<p>
  Please choose your language:
</p>
<ul>
  <li><a href="/de/">Deutsch</a></li>
  <li><a href="/en/">English</a></li>
</ul>
Arne Hartherz
Last edit
Arne Hartherz
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2016-05-24 12:29)