如何使用 Javascript 更改浏览器语言

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3753999/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:00:50  来源:igfitidea点击:

How do I change the browser language with Javascript

javascriptbrowser

提问by ammar

I want to access the user browser settings and change the browser language, is this possible using Javascript?

我想访问用户浏览器设置并更改浏览器语言,这可以使用 Javascript 吗?

If it's possible, how can I access this? (sample code please)

如果可能,我该如何访问它?(请提供示例代码)

回答by vol7ron

You can detect, but cannot set.

您可以检测,但不能设置。

var lang = navigator.language || navigator.userLanguage;

// navigator.language     : Netscape & Firefox
// navigator.userLanguage : Internet Explorer


If you want to output different languages, the best way is to do it server-side. Either:


如果要输出不同的语言,最好的方法是在服务器端进行。任何一个:

  • use an AJAX call to dynamically load the appropriate page
  • use a session variable to load the initial page correctly
  • 使用 AJAX 调用动态加载适当的页面
  • 使用会话变量正确加载初始页面

回答by Lekensteyn

No that is not possible. How would you find it if you open a page, and your browser turns Arabic (or some other language you can't read)?

不,那是不可能的。如果您打开一个页面,并且您的浏览器变成阿拉伯语(或您无法阅读的其他语言),您将如何找到它?

回答by Eric Mickelsen

This is impossible and a bad idea. A better idea is to detect the browser's language, which is possible to do reasonably well, and ask the user to change it (assuming the change is absolutely necessary).

这是不可能的,也是个坏主意。一个更好的主意是检测浏览器的语言,这可能做得相当好,并要求用户更改它(假设更改是绝对必要的)。

回答by Randy the Dev

If what you actually want to do is detect the language the user is using, which is what you want to do, because nothing will annoy your visitors more that their browser preferences getting changed, on the server-side, read the Accept-LanguageHTTP request header that all modern browsers send, it should contain all the info you need. If it is absent, assume the language of your largest audience.

如果您真正想要做的是检测用户使用的语言,这就是您想要做的,因为没有什么比他们的浏览器首选项改变更让访问者烦恼了,在服务器端,阅读Accept-LanguageHTTP 请求标头所有现代浏览器发送,它应该包含您需要的所有信息。如果它不存在,请假设您的最大受众使用的语言。

Check out RFC2616 Section 14.4for more information on Accept-Languageand it's use.

查看RFC2616 第 14.4 节以获取有关Accept-Language其使用的更多信息。

回答by Pekka

This is definitely not possible using JavaScript on a web page.

在网页上使用 JavaScript 绝对不可能做到这一点。

A browser Extension might have the rights to change this - I'm not sure, it will also depend on the browser. However, building such an extension would require a fair amount of skill and work.

浏览器扩展可能有权更改此设置 - 我不确定,这也取决于浏览器。但是,构建这样的扩展需要大量的技能和工作。