Home > Uncategorized > Detect browser locale using Javascript

Detect browser locale using Javascript

On Chrome and Firefox 32+, navigator.languages contains an array of locales in order of user preference, and is more accurate than navigator.language, however to make it backwards-compatible (Tested Chrome / IE / Firefox / Safari), then use this:

function getLang()
 if (navigator.languages != undefined) 
 return navigator.languages[0]; 
 return navigator.language;

I tested this against a more complex technique by making an ajax call to a service that returns the HTTP headers, and parsing the Accept-Language.

The server side code as follows;

<%@ Import Namespace=”System” %>
<%@ Page Language=”c#”%>
<script runat=”server”>
public string ServerSideFunction()
Response.AddHeader(“Access-Control-Allow-Origin”, “*”);
int loop1;
NameValueCollection coll;
String[] arr1 = coll.AllKeys;
string seperator = “”;
for (loop1 = 0; loop1<arr1.Length; loop1++)
Response.Write(seperator + “\”” + arr1[loop1] + “\”:”);
// Get all values under this key.
String[] arr2=coll.GetValues(arr1[loop1]);
Response.Write( “\”” + Server.HtmlEncode(arr2[0]) + “\””);
seperator = “,”;
return “”;
<% =ServerSideFunction() %>

Which is called by some JQuery script as follows;

function init()
url: “http://xxxx.xxxxx.net/Headers.aspx&#8221;,
success: function(data){
var strLanguage = data[“Accept-Language”].split(“,”)[0];
dataType: “json”

Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: