且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用javascript获取浏览器当前的语言环境首选项?

更新时间:2022-11-18 08:06:23

navigator 对象(在 IE 上也可以称为 clientInformation 但在没有理由使用这个名字):

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(非 IE,浏览器安装语言)
  • browserLanguage(IE,浏览器安装语言)
  • userLanguage(IE,用户级操作系统范围的语言设置)
  • systemLanguage(IE,操作系统安装语言)
  • 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.

您应该嗅探以决定默认使用哪种语言的正确位置(由普通浏览器 UI 配置)是 Accept-Language 标头在 HTTP 请求中传递到您的服务器.这是您可以从中选择的首选语言的排名列表,如果您使用它,它就是 ASP.NET 用来猜测自动客户端文化的内容.

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.

遗憾的是,此属性在 JavaScript 中不可用!

Unfortunately, this property is not available from JavaScript!

您通常做的是使用服务器端解析 Accept-Language 标头并从中选择一种合适的语言来使用.在 ASP.NET 中,您可以从 获取预先排序的列表HttpRequest.UserLanguages 并选择您喜欢的第一个.

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.