Detecting browser language preference with JavaScript poses challenges, particularly for settings configured in Internet Explorer and Firefox. While browsers like Chrome and Safari have properties such as navigator.language and navigator.userLanguage that provide access to language information, these properties often fail to reflect preferences set in specific browser menus.
The main issue is that browser settings do not directly affect the navigator.language property accessible through JavaScript. Instead, they impact the HTTP Accept-Language header. Unfortunately, this header is unavailable to JavaScript, leaving programmers in a quandary.
To circumvent this limitation, a workaround using a Google App Engine script (http://ajaxhttpheaders.appspot.com) has been devised. This script retrieves HTTP request headers via JSONP and returns the Accept-Language header value.
// jQuery example $.ajax({ url: "http://ajaxhttpheaders.appspot.com", dataType: 'jsonp', success: function(headers) { language = headers['Accept-Language']; nowDoSomethingWithIt(language); } });
For convenience, a jQuery plugin that wraps this functionality is available on GitHub: https://github.com/dansingerman/jQuery-Browser-Language
The following code is the core logic running on AppEngine:
class MainPage(webapp.RequestHandler): def get(self): headers = self.request.headers callback = self.request.get('callback')
The above is the detailed content of How Can JavaScript Accurately Detect User Browser Language Preferences?. For more information, please follow other related articles on the PHP Chinese website!