Posted almost 4 years ago. Visible to the public.

How to: Client-side language detection

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.

Copy
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:

Copy
<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:

Copy
<p> Please choose your language: </p> <ul> <li><a href="/de/">Deutsch</a></li> <li><a href="/en/">English</a></li> </ul>

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for old versions of Ruby on Rails (3.2 and 2.3).

Owner of this card:

Avatar
Arne Hartherz
Last edit:
almost 4 years ago
by Arne Hartherz
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more