我一直在尝试使用JavaScript检测浏览器语言首选项。

如果我在IE的“工具>Internet选项>常规>语言”中设置浏览器语言,如何使用JavaScript读取此值?

火狐也有同样的问题。我无法检测工具>选项>内容>语言使用导航器.language的设置。

使用导航器。userLanguage,它检测设置通过 打开>ControlPanel>RegionalandLanguageOptions>Regional Options选项卡。

我已经用navigator测试过了。browserLanguage和navigator。systemLanguage但都不返回第一个设置的值(Tools>InternetOptions>General>Languages)

我找到了一个详细讨论这个问题的链接,但这个问题仍然没有答案:(


当前回答

Dan Singerman的回答有一个问题,因为jQuery ajax的异步特性,获取的头文件必须立即使用。但是,使用他的谷歌应用服务器,我编写了以下内容,以便将报头设置为初始设置的一部分,并可以在以后使用。

<html>
<head>
<script>

    var bLocale='raw'; // can be used at any other place

    function processHeaders(headers){
        bLocale=headers['Accept-Language'];
        comma=bLocale.indexOf(',');
        if(comma>0) bLocale=bLocale.substring(0, comma);
    }

</script>

<script src="jquery-1.11.0.js"></script>

<script type="application/javascript" src="http://ajaxhttpheaders.appspot.com?callback=processHeaders"></script>

</head>
<body>

<h1 id="bLocale">Should be the browser locale here</h1>

</body>

<script>

    $("#bLocale").text(bLocale);

</script>
</html>

其他回答

导航器。用于IE的userLanguage

窗口.导航员.萤火虫/歌剧/safari语言

如果您不想依赖外部服务器,并且您有自己的服务器,您可以使用一个简单的PHP脚本来实现与@DanSingerman answer相同的行为。

languageDetector.php:

<?php
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
echo json_encode($lang);
?>

只需从jQuery脚本中更改这几行:

url: "languageDetector.php",
dataType: 'json',
success: function(language) {
    nowDoSomethingWithIt(language);
}

Var语言=导航器。语言和导航器。// Chrome / Firefox . languages[0] || 导航器。language || //所有浏览器 navigator.userLanguage;// IE <= 10 console.log(语言);

https://developer.mozilla.org/en-US/docs/Web/API/NavigatorLanguage/languages https://developer.mozilla.org/en-US/docs/Web/API/NavigatorLanguage/language

尝试PWA模板https://github.com/StartPolymer/progressive-web-app-template

对于正在寻找Java服务器解决方案的人

这里是RestEasy

@GET
@Path("/preference-language")
@Consumes({"application/json", "application/xml"})
@Produces({"application/json", "application/xml"})
public Response getUserLanguagePreference(@Context HttpHeaders headers) {
    return Response.status(200)
            .entity(headers.getAcceptableLanguages().get(0))
            .build();
}

我也遇到了同样的问题,于是我编写了以下前端专用库,它为多种浏览器打包了代码。代码并不多,但不用在多个网站上复制和粘贴相同的代码。

Get it: acceptedlanguages.js

使用它:

<script src="acceptedlanguages.js"></script>
<script type="text/javascript">
  console.log('Accepted Languages:  ' + acceptedlanguages.accepted);
</script>

它总是返回一个数组,按用户偏好排序。在Safari和IE中,数组总是单长度的。在FF和Chrome中,它可能不止一种语言。