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

走远了吗. 提交于 2019-12-01 06:34:35

问题


Do web browsers have an interface to access any of the locale settings as set in the operating system by the user?

I can detect what country the user is currently in from their IP address or using a the new geolocation API, but I'm writing a browser app for travellers so I expect their current location to often not be their home country.

Is there any way to determine what country/locale the browser/OS is set to?

If not is there any proposal to add proper locale support to JavaScript?

Also are there any clever workarounds? (For instance I know I can get the user's preferred browsing language but there are plenty of countries which use the same language and plenty of users who keep this set to the default rather than changing it to their usual language.)


回答1:


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




回答2:


I'd have to defend or re-state the answers of SReject and CodeJack because the browser language does in general contain the country locale of the OS as in "en-US" or "de-CH".

We've used this for years to pre-select the country in forms and it works in enough cases to be useful.

So with travelling Swiss users you would use navigator.language.slice(-2) and get "CH" which is a valid answer to your question.




回答3:


var userLocale = navigator.language or

navigator.userLanguage;

EDIT only other way is geoLocation API of HTML5

http://html5demos.com/geo http://dev.w3.org/geo/api/spec-source.html



来源:https://stackoverflow.com/questions/11826149/is-it-possible-to-determine-the-user-locales-country-as-set-in-the-os-from

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!