javascript 如何更改浏览器接受语言

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18522940/
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-10-27 12:15:49  来源:igfitidea点击:

How do I change the browser accept-language

javascriptjqueryasp.net-mvc-4localization

提问by Sinaesthetic

If the user has their browser set to fr-CA, for instance but my site has the option to view the page in another available language (like English). How can I override the accept-language header so that I can reload using the specified language?

例如,如果用户将浏览器设置为 fr-CA,但我的网站可以选择以另一种可用语言(如英语)查看页面。如何覆盖 accept-language 标头,以便可以使用指定的语言重新加载?

I was attempting to simply change the Accept-Language header and then reload the page, but I'm not sure how to do this. Any thoughts?

我试图简单地更改 Accept-Language 标头,然后重新加载页面,但我不确定如何执行此操作。有什么想法吗?

UPDATE: Ok, so I'm getting people explaining to me what localization is so I must not have asked this properly.

更新:好的,所以我让人们向我解释什么是本地化,所以我一定没有正确地提出这个问题。

My site currently has globalization set to auto in the web.config so it will automatically set the thread culture to whichever language was negotiated at app start. By default, the user's browser will send the accept-language header based on the language settings for the browser which, like someone pointed out below, average users have no clue what those are, where those are, or how to change them. In any case, let's call this default behavior that the browser will handle the language headers first. However, as a FEATURE, I want to allow the user to change this accept-language header from the page. For instance, in the application, the language settings will normally be determined by cookie or by user preference (via profile settings), but on the landing/login page (particularly if this your first time logging in on a certain computer), I have no idea who you are so I only have your browser settings to go off of. But let's say that you're traveling on business and accessing this site from an american computer, the page loads in English and you can't read it and you have no idea how to change the browser language. Would it not be nice to have the option to choose your language from a drop down menu or icon or something? I think it would be.

我的网站目前在 web.config 中将全球化设置为自动,因此它会自动将线程文化设置为在应用程序启动时协商的任何语言。默认情况下,用户的浏览器将根据浏览器的语言设置发送 accept-language 标头,就像下面有人指出的那样,普通用户不知道那些是什么,它们在哪里,或者如何更改它们。在任何情况下,我们都将这种默认行为称为浏览器将首先处理语言标题。但是,作为一项功能,我希望允许用户从页面更改此接受语言标题。例如,在应用程序中,语言设置通常由 cookie 或用户偏好(通过配置文件设置)决定,但在登陆/登录页面上(特别是如果这是您第一次在某台计算机上登录),我不知道你是谁,所以我只能关闭你的浏览器设置。但是,假设您正在出差并从美国计算机访问此站点,页面以英语加载,但您无法阅读它,并且您不知道如何更改浏览器语言。可以选择从下拉菜单或图标或其他东西中选择您的语言不是很好吗?我想会的。

So in order to do that, I need to be able to change that accept-language header and reload the page. This is where I'm not sure how to proceed.

因此,为了做到这一点,我需要能够更改接受语言标题并重新加载页面。这是我不确定如何进行的地方。

I've tried navigator.language = <selected language>and xhr.setRequestHeaderbut these don't seem to work.

我试过了navigator.language = <selected language>xhr.setRequestHeader但这些似乎不起作用。

采纳答案by Raciel R.

I might be wrong but the locale settings is not something you change in your code. This is determined by the browser's user configuration. If you are using an HttpClient you definitely send the value you want for Accept-Language header to the server, but don't expect to change this from your code and make it effective in ALL the requests originated in the browser.

我可能是错的,但区域设置不是您在代码中更改的内容。这是由浏览器的用户配置决定的。如果您使用的是 HttpClient,您肯定会将您想要的 Accept-Language 标头的值发送到服务器,但不要期望从您的代码中更改它并使其在浏览器中发起的所有请求中都有效。

Common practice is to set a custom cookie with your user's language preference. By default you should populate this cookie with the value on Accept-Language header. In ASP.NET MVC there is a setting so both Thread.CurrentThread.CurrentCultureand Thread.CurrentThread.CurrentUICulture get's set according to the user's browser configuration:

通常的做法是使用您用户的语言首选项设置自定义 cookie。默认情况下,您应该使用 Accept-Language 标头上的值填充此 cookie。在 ASP.NET MVC 中有一个设置,因此Thread.CurrentThread.CurrentCulture和 Thread.CurrentThread.CurrentUICulture 都根据用户的浏览器配置进行设置:

<system.web>
    <globalization enableClientBasedCulture="true" uiCulture="auto" culture="auto" />
</system.web>

You can then create an ActionFilter that would check the custom language cookie and will set the Thread.CurrentThread.CurrentUICultureaccordingly.

然后,您可以创建一个 ActionFilter 来检查自定义语言 cookie 并相应地设置Thread.CurrentThread.CurrentUICulture

Thread.CurrentThread.CurrentUICulture is used to determine which resources the code should use. While Thread.CurrentThread.CurrentCulture is used for all the numeric and dates handling.

Thread.CurrentThread.CurrentUICulture 用于确定代码应该使用哪些资源。而 Thread.CurrentThread.CurrentCulture 用于所有数字和日期处理。

This is how that action filter might look like:

这就是操作过滤器的样子:

public class LanguageActionFilter : IActionFilter
{
    public void OnActionExecuted(ActionExecutedContext filterContext)
    {
    }

    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var langCookie = GetOrSetLanguageCookie(filterContext.HttpContext);
        var culture = new CultureInfo(langCookie.Value);

        Thread.CurrentThread.CurrentUICulture = culture;
    }

    private HttpCookie GetOrSetLanguageCookie(HttpContextBase context)
    {
        var cookie = context.Request.Cookies[Constants.LanguageCookieName];
        if (cookie == null)
        {
            //set the cookie for first time
            cookie = new HttpCookie(Constants.LanguageCookieName, Thread.CurrentThread.CurrentUICulture.Name)
            {
                Expires = DateTime.Now.AddYears(1),
                Path = "/"
            };
            context.Response.Cookies.Add(cookie);
        }
        return cookie;
    }
}

Pleae Note:

请注意:

  • Even when your user selects, let's say "es-Ar" in your interface, and you set your UICulture accordingly for that user, IF the user's browser is configured with en-US dates posted for that user will be parse using the English convention, so float number will.
  • 即使您的用户选择,让我们在您的界面中说“es-Ar”,并且您相应地为该用户设置您的 UICulture,如果用户的浏览器配置为为该用户发布的 en-US 日期将使用英语约定进行解析,所以浮点数会。

IE: If the user in USA with a browser set to en_US chooses to use the Spanish interface of your app, when this user post information to the server dates like:

IE:如果浏览器设置为 en_US 的美国用户选择使用您的应用程序的西班牙语界面,则该用户向服务器发布信息的日期如下:

1/5/2015 will be parse as January 5th in the server, rather than May 1st.

1/5/2015 将在服务器中解析为 1 月 5 日,而不是 5 月 1 日。

Numbers like 1,900 will be parsed as 1900 in the server rather than 1.900.

像 1,900 这样的数字在服务器中将被解析为 1900 而不是 1.900。

I learned this the hard way. I have a question herethat was never answered.

我经过惨痛的教训才学到这个。我在这里有一个从未得到回答的问题。

Please let me know if you have any questions.

请让我知道,如果你有任何问题。

回答by Jukka K. Korpela

The Accept-Languageheader is a request header, so it is sent by the browser (or other client software). On your server, you can ignore it by doing nothing. That is, it has no effect as such; all depends on whether your server-side code recognizes it and takes some action. So you cannot and need not change the header sent by the browser.

所述Accept-Language报头是请求报头,所以它是由浏览器(或其他客户端软件)发送。在您的服务器上,您可以什么都不做就忽略它。也就是说,它本身没有效果;一切都取决于您的服务器端代码是否识别它并采取一些行动。因此,您不能也不需要更改浏览器发送的标头。

The user can change the Accept-Languageheader sent by the browser using the browser's preference settings. E.g., in Chrome, go to “Settings”, click on “Show advanced settings...”, scroll down to “Languages”, click on “Language and input settings...”, and then add languages and drag to order them.

用户可以Accept-Language使用浏览器的首选项设置更改浏览器发送的标头。例如,在 Chrome 中,转到“设置”,单击“显示高级设置...”,向下滚动到“语言”,单击“语言和输入设置...”,然后添加语言并拖动以进行排序.

This is not something people do often, and most people have no idea of the existence of such settings. So what the browser sends is usually some factory defaults. They can be rather strange, e.g. Accept-Language: fr-CAwould mean, by the protocol, “if you, dear server, have different language versions of the resource I'm requesting for, please give me Canadian French; if you don't have it, I don't care which version you give”. This means that if the resource exists in generic French (of French French), or in English, these would have no preference over, say, Swahili or Volapük version. So a more sensible header would normally be Accept-Language: fr-CA, fr, en, and this is in practice how you should deal with Accept-Language: fr-CA.

这不是人们经常做的事情,大多数人都不知道此类设置的存在。所以浏览器发送的通常是一些出厂默认值。它们可能很奇怪,例如Accept-Language: fr-CA,根据协议,“如果您,亲爱的服务器,有我请求的资源的不同语言版本,请给我加拿大法语;如果你没有它,我不在乎你给出哪个版本”。这意味着如果资源以通用法语(法语法语)或英语存在,则这些资源不会优先于斯瓦希里语或 Volapük 版本。所以一个更明智的标题通常是Accept-Language: fr-CA, fr, en,这实际上是你应该如何处理的Accept-Language: fr-CA