How to Determine User's Locale Within Browser

How to determine user's locale within browser?

The proper way is to look at the HTTP Accept-Language header sent to the server. This contains the ordered, weighted list of languages the user has configured their browser to prefer.

Unfortunately this header is not available for reading inside JavaScript; all you get is navigator.language, which tells you what localised version of the web browser was installed. This is not necessarily the same thing as the user's preferred language(s). On IE you instead get systemLanguage (OS installed language), browserLanguage (same as language) and userLanguage (user configured OS region), which are all similarly unhelpful.

If I had to choose between those properties, I'd sniff for userLanguage first, falling back to language and only after that (if those didn't match any available language) looking at browserLanguage and finally systemLanguage.

If you can put a server-side script somewhere else on the net that simply reads the Accept-Language header and spits it back out as a JavaScript file with the header value in the string, eg.:

var acceptLanguage= 'en-gb,en;q=0.7,de;q=0.3';

then you could include a <script src> pointing at that external service in the HTML, and use JavaScript to parse the language header. I don't know of any existing library code to do this, though, since Accept-Language parsing is almost always done on the server side.

Whatever you end up doing, you certainly need a user override because it will always guess wrong for some people. Often it's easiest to put the language setting in the URL (eg. http​://www.example.com/en/site vs http​://www.example.com/de/site), and let the user click links between the two. Sometimes you do want a single URL for both language versions, in which case you have to store the setting in cookies, but this may confuse user agents with no support for cookies and search engines.

JavaScript for detecting browser language preference

I think the main problem here is that the browser settings don't actually affect the navigator.language property that is obtained via javascript.

What they do affect is the HTTP 'Accept-Language' header, but it appears this value is not available through javascript at all. (Probably why @anddoutoi states he can't find a reference for it that doesn't involve server side.)

I have coded a workaround: I've knocked up a google app engine script at http://ajaxhttpheaders.appspot.com that will return you the HTTP request headers via JSONP.

(Note: this is a hack only to be used if you do not have a back end available that can do this for you. In general you should not be making calls to third party hosted javascript files in your pages unless you have a very high level of trust in the host.)

I intend to leave it there in perpetuity so feel free to use it in your code.

Here's some example code (in jQuery) for how you might use it

$.ajax({ 
url: "http://ajaxhttpheaders.appspot.com",
dataType: 'jsonp',
success: function(headers) {
language = headers['Accept-Language'];
nowDoSomethingWithIt(language);
}
});

Hope someone finds this useful.

Edit: I have written a small jQuery plugin on github that wraps this functionality: https://github.com/dansingerman/jQuery-Browser-Language

Edit 2: As requested here is the code that is running on AppEngine (super trivial really):

class MainPage(webapp.RequestHandler):
def get(self):
headers = self.request.headers
callback = self.request.get('callback')

if callback:
self.response.headers['Content-Type'] = 'application/javascript'
self.response.out.write(callback + "(")
self.response.out.write(headers)
self.response.out.write(")")
else:
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write("I need a callback=")

application = webapp.WSGIApplication(
[('/', MainPage)],
debug=False)

def main():
run_wsgi_app(application)

if __name__ == "__main__":
main()

Edit3: Have open sourced the app engine code here: https://github.com/dansingerman/app-engine-headers

Is it possible to determine the user locale's **country** as set in the OS from the browser in JavaScript?

The best you'll get is languages:

  • navigator.language (Netscape - Browser Localization)
  • navigator.browserLanguage (IE-Specific - Browser Localized Language)
  • navigator.systemLanguage (IE-Specific - Windows OS - Localized Language)
  • navigator.userLanguage

Due to either security concerns or just not implemented, what you have requested is not possible, natively. You can however use an ActiveX object for your Windows users

You could have a user select their perfered language, country, etc then use javascript to set a cookie, which will be sent to your server anytime a page is requested

How to getting browser current locale preference using javascript?

The following properties exist on the navigator object (which can also be known as clientInformation on IE but there's no reason ever to use that name):

  • language (non-IE, browser install language)
  • browserLanguage (IE, browser install language)
  • userLanguage (IE, user-level OS-wide language setting)
  • systemLanguage (IE, OS installation language)

But! You should never use any of these properties! They will be the wrong language in many cases.

None of them reflect the language settings the user actually gets to configure in the browser's ‘preferred languages’ UI, and they are difficult-to-impossible for users to change. You will cause big frustration by using any of these values without an additional easy manual way to switch languages.

The correct place you should sniff to decide what language to use by default, as configured by the normal browser UI, is the Accept-Language header passed to your server in the HTTP request. This is a ranked list of preferred languages from which you can pick, and it's what ASP.NET uses to guess an automatic client Culture, if you use that.

Unfortunately, this property is not available from JavaScript!

What you typically do is use your server side to parse the Accept-Language header and choose a single appropriate language to use from it. In ASP.NET you can get a pre-sorted list from HttpRequest.UserLanguages and pick the first that you like.

You then spit that language name out into a <script> element to pass the language information to the client side.

How to determine users locale date format using javascript (format is dd/mm or mm/dd)?

Using moment localeData you can get localized longDateFormat. This will give you localized format for year, month and day. You can use this value to parse your input string locale-aware.

Here a live example:

// Get user localevar locale = window.navigator.userLanguage || window.navigator.language;// Set locale to momentmoment.locale(locale);
// Get locale datavar localeData = moment.localeData();var format = localeData.longDateFormat('L');
var m1 = moment('2/2/2016', format);console.log(m1.format()); // February 2nd 2016console.log(m1.format(format) + ' using format: ' + format);
var m2 = moment('5/1/2017', format);console.log(m2.format());console.log(m2.format(format) + ' using format: ' + format);// January 5th 2017 for locales that use DD/MM/YYYY// May 1st 2017 for locales that use MM/DD/YYYY
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment-with-locales.min.js"></script>

How to get the browser language using JavaScript

Try this script to get your browser language

<script type="text/javascript">var userLang = navigator.language || navigator.userLanguage; alert ("The language is: " + userLang);</script>


Related Topics



Leave a reply



Submit