Read more

How to: Client-side language detection

Arne Hartherz
May 24, 2016Software engineer at makandra GmbH

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

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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>
Posted by Arne Hartherz to makandra dev (2016-05-24 14:29)