[javascript] JavaScript for detecting browser language preference

I have been trying to detect the browser language preference using JavaScript.

If I set the browser language in IE in Tools>Internet Options>General>Languages, how do I read this value using JavaScript?

Same problem for Firefox. I'm not able to detect the setting for tools>options>content>languages using navigator.language.

Using navigator.userLanguage , it detects the setting done thru Start>ControlPanel>RegionalandLanguageOptions>Regional Options tab.

I have tested with navigator.browserLanguage and navigator.systemLanguage but neither returns the value for the first setting(Tools>InternetOptions>General>Languages)

I found a link which discusses this in detail, but the question remains unanswered :(

This question is related to javascript localization internationalization

The answer is


If you have control of a backend and are using django, a 4 line implementation of Dan's idea is:

def get_browser_lang(request):
if request.META.has_key('HTTP_ACCEPT_LANGUAGE'):
    return JsonResponse({'response': request.META['HTTP_ACCEPT_LANGUAGE']})
else:
    return JsonResponse({'response': settings.DEFAULT_LANG})

then in urls.py:

url(r'^browserlang/$', views.get_browser_lang, name='get_browser_lang'),

and on the front end:

$.get(lg('SERVER') + 'browserlang/', function(data){
    var lang_code = data.response.split(',')[0].split(';')[0].split('-')[0];
});

(you have to set DEFAULT_LANG in settings.py of course)


i had a diffrent approach, this might help someone in the future:

the customer wanted a page where you can swap languages. i needed to format numbers by that setting (not the browser setting / not by any predefined setting)

so i set an initial setting depending on the config settings (i18n)

$clang = $this->Session->read('Config.language');
echo "<script type='text/javascript'>var clang = '$clang'</script>";

later in the script i used a function to determine what numberformating i need

function getLangsettings(){
  if(typeof clang === 'undefined') clang = navigator.language;
  //console.log(clang);
  switch(clang){
    case 'de':
    case 'de-de':
        return {precision : 2, thousand : ".", decimal : ","}
    case 'en':
    case 'en-gb':
    default:
        return {precision : 2, thousand : ",", decimal : "."}
  }
}

so i used the set language of the page and as a fallback i used the browser settings.

which should be helpfull for testing purposes aswell.

depending on your customers you might not need that settings.


Javascript way:

var language = window.navigator.userLanguage || window.navigator.language;//returns value like 'en-us'

If you are using jQuery.i18n plugin, you can use:

jQuery.i18n.browserLang();//returns value like '"en-US"'

I've been using Hamid's answer for a while, but it in cases where the languages array is like ["en", "en-GB", "en-US", "fr-FR", "fr", "en-ZA"] it will return "en", when "en-GB" would be a better match.

My update (below) will return the first long format code e.g. "en-GB", otherwise it will return the first short code e.g. "en", otherwise it will return null.

_x000D_
_x000D_
function getFirstBrowserLanguage() {_x000D_
        var nav = window.navigator,_x000D_
            browserLanguagePropertyKeys = ['language', 'browserLanguage', 'systemLanguage', 'userLanguage'],_x000D_
            i,_x000D_
            language,_x000D_
            len,_x000D_
            shortLanguage = null;_x000D_
_x000D_
        // support for HTML 5.1 "navigator.languages"_x000D_
        if (Array.isArray(nav.languages)) {_x000D_
            for (i = 0; i < nav.languages.length; i++) {_x000D_
                language = nav.languages[i];_x000D_
                len = language.length;_x000D_
                if (!shortLanguage && len) {_x000D_
                    shortLanguage = language;_x000D_
                }_x000D_
                if (language && len>2) {_x000D_
                    return language;_x000D_
                }_x000D_
            }_x000D_
        }_x000D_
_x000D_
        // support for other well known properties in browsers_x000D_
        for (i = 0; i < browserLanguagePropertyKeys.length; i++) {_x000D_
            language = nav[browserLanguagePropertyKeys[i]];_x000D_
            //skip this loop iteration if property is null/undefined.  IE11 fix._x000D_
            if (language == null) { continue; } _x000D_
            len = language.length;_x000D_
            if (!shortLanguage && len) {_x000D_
                shortLanguage = language;_x000D_
            }_x000D_
            if (language && len > 2) {_x000D_
                return language;_x000D_
            }_x000D_
        }_x000D_
_x000D_
        return shortLanguage;_x000D_
    }_x000D_
_x000D_
console.log(getFirstBrowserLanguage());
_x000D_
_x000D_
_x000D_

Update: IE11 was erroring when some properties were undefined. Added a check to skip those properties.


For what it's worth, Wikimedia's Universal Language Selector library has hooks for doing this: https://www.mediawiki.org/wiki/Extension:UniversalLanguageSelector

See the function getFrequentLanguageList in resources/js/ext.uls.init.js . Direct link: https://gerrit.wikimedia.org/r/gitweb?p=mediawiki/extensions/UniversalLanguageSelector.git;a=blob;f=resources/js/ext.uls.init.js;hb=HEAD

It still depends on the server, or more specifically, the MediaWiki API. The reason I'm showing it is that it may provide a good example of getting all the useful information about the user's language: browser language, Accept-Language, geolocation (with getting country/language info from the CLDR), and of course, user's own site preferences.


_x000D_
_x000D_
let lang = window.navigator.languages ? window.navigator.languages[0] : null;_x000D_
    lang = lang || window.navigator.language || window.navigator.browserLanguage || window.navigator.userLanguage;_x000D_
_x000D_
let shortLang = lang;_x000D_
if (shortLang.indexOf('-') !== -1)_x000D_
    shortLang = shortLang.split('-')[0];_x000D_
_x000D_
if (shortLang.indexOf('_') !== -1)_x000D_
    shortLang = shortLang.split('_')[0];_x000D_
_x000D_
console.log(lang, shortLang);
_x000D_
_x000D_
_x000D_

I only needed the primary component for my needs, but you can easily just use the full string. Works with latest Chrome, Firefox, Safari and IE10+.


If you only need to support certain modern browsers then you can now use:

navigator.languages

which returns an array of the user's language preferences in the order specified by the user.

As of now (Sep 2014) this works on: Chrome (v37), Firefox (v32) and Opera (v24)

But not on: IE (v11)


For who are looking for Java Server solution

Here is RestEasy

@GET
@Path("/preference-language")
@Consumes({"application/json", "application/xml"})
@Produces({"application/json", "application/xml"})
public Response getUserLanguagePreference(@Context HttpHeaders headers) {
    return Response.status(200)
            .entity(headers.getAcceptableLanguages().get(0))
            .build();
}

I can't find a single reference that state that it's possible without involving the serverside.

MSDN on:

From browserLanguage:

In Microsoft Internet Explorer 4.0 and earlier, the browserLanguage property reflects the language of the installed browser's user interface. For example, if you install a Japanese version of Windows Internet Explorer on an English operating system, browserLanguage would be ja.

In Internet Explorer 5 and later, however, the browserLanguage property reflects the language of the operating system regardless of the installed language version of Internet Explorer. However, if Microsoft Windows 2000 MultiLanguage version is installed, the browserLanguage property indicates the language set in the operating system's current menus and dialogs, as found in the Regional Options of the Control Panel. For example, if you install a Japanese version of Internet Explorer 5 on an English (United Kingdom) operating system, browserLanguage would be en-gb. If you install Windows 2000 MultiLanguage version and set the language of the menus and dialogs to French, browserLanguage would be fr, even though you have a Japanese version of Internet Explorer.

Note This property does not indicate the language or languages set by the user in Language Preferences, located in the Internet Options dialog box.

Furthermore, it looks like browserLanguage is deprecated cause IE8 doesn't list it


I came across this piece of code to detect browser's language in Angular Translate module, which you can find the source here. I slightly modified the code by replacing angular.isArray with Array.isArray to make it independent of Angular library.

_x000D_
_x000D_
var getFirstBrowserLanguage = function () {_x000D_
    var nav = window.navigator,_x000D_
    browserLanguagePropertyKeys = ['language', 'browserLanguage', 'systemLanguage', 'userLanguage'],_x000D_
    i,_x000D_
    language;_x000D_
_x000D_
    // support for HTML 5.1 "navigator.languages"_x000D_
    if (Array.isArray(nav.languages)) {_x000D_
      for (i = 0; i < nav.languages.length; i++) {_x000D_
        language = nav.languages[i];_x000D_
        if (language && language.length) {_x000D_
          return language;_x000D_
        }_x000D_
      }_x000D_
    }_x000D_
_x000D_
    // support for other well known properties in browsers_x000D_
    for (i = 0; i < browserLanguagePropertyKeys.length; i++) {_x000D_
      language = nav[browserLanguagePropertyKeys[i]];_x000D_
      if (language && language.length) {_x000D_
        return language;_x000D_
      }_x000D_
    }_x000D_
_x000D_
    return null;_x000D_
  };_x000D_
_x000D_
console.log(getFirstBrowserLanguage());
_x000D_
_x000D_
_x000D_


navigator.userLanguage for IE

window.navigator.language for firefox/opera/safari


DanSingerman has a very good solution for this question.

The only reliable source for the language is in the HTTP-request header. So you need a server-side script to reply the request-header or at least the Accept-Language field back to you.

Here is a very simple Node.js server which should be compatible with DanSingermans jQuery plugin.

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end(JSON.stringify(req.headers));
}).listen(80,'0.0.0.0');

If you are using ASP .NET MVC and you want to get the Accepted-Languages header from JavaScript then here is a workaround example that does not involve any asynchronous requests.

In your .cshtml file, store the header securely in a div's data- attribute:

<div data-languages="@Json.Encode(HttpContext.Current.Request.UserLanguages)"></div>

Then your JavaScript code can access the info, e.g. using JQuery:

<script type="text/javascript">
$('[data-languages]').each(function () {
    var languages = $(this).data("languages");
    for (var i = 0; i < languages.length; i++) {
        var regex = /[-;]/;
        console.log(languages[i].split(regex)[0]);
    }
});
</script>

Of course you can use a similar approach with other server technologies as others have mentioned.


If you are developing a Chrome App / Extension use the chrome.i18n API.

chrome.i18n.getAcceptLanguages(function(languages) {
  console.log(languages);
  // ["en-AU", "en", "en-US"]
});

If you don't want to rely on an external server and you have one of your own you can use a simple PHP script to achieve the same behavior as @DanSingerman answer.

languageDetector.php:

<?php
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
echo json_encode($lang);
?>

And just change this lines from the jQuery script:

url: "languageDetector.php",
dataType: 'json',
success: function(language) {
    nowDoSomethingWithIt(language);
}

First of all, excuse me for my English. I would like to share my code, because it works and it is different than the others given anwers. In this exemple,if you speak French (France, Belgium or other french language) you are redirected on the french page, otherwise on the english page, depending on the browser configuration :

_x000D_
_x000D_
<script type="text/javascript">_x000D_
        $(document).ready(function () {_x000D_
            var userLang = navigator.language || navigator.userLanguage;_x000D_
            if (userLang.startsWith("fr")) {_x000D_
                    window.location.href = '../fr/index.html';_x000D_
                }_x000D_
            else {_x000D_
                    window.location.href = '../en/index.html';_x000D_
                }_x000D_
            });_x000D_
    </script>
_x000D_
_x000D_
_x000D_


I've just come up with this. It combines newer JS destructuring syntax with a few standard operations to retrieve the language and locale.

var [lang, locale] = (
    (
        (
            navigator.userLanguage || navigator.language
        ).replace(
            '-', '_'
        )
    ).toLowerCase()
).split('_');

Hope it helps someone


I have a hack that I think uses very little code and is quite reliable.

Put your site's files in a subdirectory. SSL into your server and create symlinks to that subdirectory where your files are stored that indicate your languages.

Something like this:

ln -s /var/www/yourhtml /var/www/en
ln -s /var/www/yourhtml /var/www/sp
ln -s /var/www/yourhtml /var/www/it

Use your web server to read HTTP_ACCEPT_LANGUAGE and redirect to these "different subdirectories" according to the language value it provides.

Now you can use Javascript's window.location.href to get your url and use it in conditionals to reliably identify the preferred language.

url_string = window.location.href;
if (url_string = "http://yoursite.com/it/index.html") {
    document.getElementById("page-wrapper").className = "italian";
}

var language = window.navigator.userLanguage || window.navigator.language;
alert(language); //works IE/SAFARI/CHROME/FF

window.navigator.userLanguage is IE only and it's the language set in Windows Control Panel - Regional Options and NOT browser language, but you could suppose that a user using a machine with Window Regional settings set to France is probably a French user.

navigator.language is FireFox and all other browser.

Some language code: 'it' = italy, 'en-US' = english US, etc.


As pointed out by rcoup and The WebMacheter in comments below, this workaround won't let you discriminate among English dialects when users are viewing website in browsers other than IE.

window.navigator.language (Chrome/FF/Safari) returns always browser language and not browser's preferred language, but: "it's pretty common for English speakers (gb, au, nz, etc) to have an en-us version of Firefox/Chrome/Safari." Hence window.navigator.language will still return en-US even if the user preferred language is en-GB.


Dan Singerman's answer has an issue that the header fetched has to be used right away, due to the asynchronous nature of jQuery's ajax. However, with his google app server, I wrote the following, such that the header is set as part of the initial set up and can be used at later time.

<html>
<head>
<script>

    var bLocale='raw'; // can be used at any other place

    function processHeaders(headers){
        bLocale=headers['Accept-Language'];
        comma=bLocale.indexOf(',');
        if(comma>0) bLocale=bLocale.substring(0, comma);
    }

</script>

<script src="jquery-1.11.0.js"></script>

<script type="application/javascript" src="http://ajaxhttpheaders.appspot.com?callback=processHeaders"></script>

</head>
<body>

<h1 id="bLocale">Should be the browser locale here</h1>

</body>

<script>

    $("#bLocale").text(bLocale);

</script>
</html>

Based on the answer here Accessing the web page's HTTP Headers in JavaScript I built the following script to get the browser language:

var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var headers = req.getAllResponseHeaders().toLowerCase();
var contentLanguage = headers.match( /^content-language\:(.*)$/gm );
if(contentLanguage[0]) {
    return contentLanguage[0].split(":")[1].trim().toUpperCase();
}

There is no decent way to get that setting, at least not something browser independent.

But the server has that info, because it is part of the HTTP request header (the Accept-Language field, see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4)

So the only reliable way is to get an answer back from the server. You will need something that runs on the server (like .asp, .jsp, .php, CGI) and that "thing" can return that info. Good examples here: http://www.developershome.com/wap/detection/detection.asp?page=readHeader


Update of year 2014.

Now there is a way to get Accept-Languages in Firefox and Chrome using navigator.languages (works in Chrome >= 32 and Firefox >= 32)

Also, navigator.language in Firefox these years reflects most preferred language of content, not language of UI. But since this notion is yet to be supported by other browsers, it is not very useful.

So, to get most preferred content language when possible, and use UI language as fallback:

navigator.languages
    ? navigator.languages[0]
    : (navigator.language || navigator.userLanguage)

_x000D_
_x000D_
var language = navigator.languages && navigator.languages[0] || // Chrome / Firefox_x000D_
               navigator.language ||   // All browsers_x000D_
               navigator.userLanguage; // IE <= 10_x000D_
_x000D_
console.log(language);
_x000D_
_x000D_
_x000D_

Try PWA Template https://github.com/StartPolymer/progressive-web-app-template


I had the same problem, and I wrote the following front-end only library that wraps up the code for multiple browsers. It's not much code, but nice to not have to copy and paste the same code across multiple websites.

Get it: acceptedlanguages.js

Use it:

<script src="acceptedlanguages.js"></script>
<script type="text/javascript">
  console.log('Accepted Languages:  ' + acceptedlanguages.accepted);
</script>

It always returns an array, ordered by users preference. In Safari & IE the array is always single length. In FF and Chrome it may be more than one language.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to localization

What's NSLocalizedString equivalent in Swift? Best practice multi language website Best practice for localization and globalization of strings and labels How to change language of app when user selects language? Lint: How to ignore "<key> is not translated in <language>" errors? Using ResourceManager How do I set the default locale in the JVM? What is the list of supported languages/locales on Android? Android: how to get the current day of the week (Monday, etc...) in the user's language? Get the current language in device

Examples related to internationalization

Best practice multi language website hardcoded string "row three", should use @string resource Android: how to get the current day of the week (Monday, etc...) in the user's language? How to use UTF-8 in resource properties with ResourceBundle HTML meta tag for content language What is the significance of 1/1/1753 in SQL Server? List of All Locales and Their Short Codes? How does internationalization work in JavaScript? PHP function to make slug (URL string) How to force NSLocalizedString to use a specific language