获取访问者语言 &带有javascript的国家代码(客户端)

问题:是否有 javascript(客户端)代码来获取访问者的国家/语言代码,准确且跨现代"浏览器?我正在寻找 'en-US''sv-SE''nl-NL' 等结果.

Question: Is there a javascript (client-side) code to get visitors country/language code, that is accurate and is cross-"modern"-browser ? I am looking for results like 'en-US', 'sv-SE', 'nl-NL', etc.

之前已经提出过与此相关的问题(一些 SO 链接:1,2,3,4 等),但我没有找到答案,有些答案已经有几年的历史了,在某些情况下指的是更老的文章,这使得我认为对此有新的解决方案.

Related questions to this have been asked before (some SO links: 1,2,3,4, among others) but I didn't find answer and some of the answers are some yearls old and in some cases referring to even more old articles, which makes me think there are new solutions for this.

我试过了:

var language = window.navigator.userLanguage || window.navigator.language;
console.log(language);

在 Chrome 中获得 "sv",在 Firefox 中获得 "en-GB",在同一台机器上,同一地点.

and got "sv" in Chrome and "en-GB" in Firefox, in the same machine, same place.

推荐答案

navigator.language 如您的链接问题之一所述并不可靠.

navigator.language isn't reliable as one of your linked questions states.

这个问题被问了很多,但你仍在搜索的原因说明了这个问题.客户端的语言检测纯粹并不可靠.

The reason this is asked a lot, but you're still searching says something about the problem. That language detection purely on the client side is not anything close to reliable.

首先,语言首选项只能用于检测语言首选项 - 即不是位置.我的浏览器设置为 en_US,因为我想要英文版.但我在英国,所以必须将其更改为 en_GB 才能通过我的浏览器设置检测到我的国家.作为客户",这不是我的问题.这对语言来说很好,但如果您网站上的所有价格都是美元,那就不好了.

First of all language preferences should only be used to detect language preferences - i.e. not location. My browser is set to en_US, because I wanted the English version. But I'm in the UK, so would have to alter this to en_GB to have my country detected via my browser settings. As the 'customer' that's not my problem. That's fine for language, but no good if all the prices on your site are in $USD.

要检测语言,您确实需要访问服务器端脚本.如果您不是后端开发人员并且想在客户端做尽可能多的事情(作为您的问题),那么您只需要一个 PHP 脚本来回显 Accept-Language 标题.最简单的可能是:

To detect language you really do need access to a server side script. If you're not a back end dev and want to do as much as possible on the client side (as your question), all you need is a one line PHP script that echos back the Accept-Language header. At its simplest it could just be:

<?php
echo $_SERVER['HTTP_ACCEPT_LANGUAGE']; 
// e.g. "en-US,en;q=0.8"

您可以通过 Ajax 获取它并解析文本响应客户端,例如(使用 jQuery):

You could get this via Ajax and parse the text response client side, e.g (using jQuery):

$.ajax( { url: 'script.php', success: function(raw){
    var prefs = raw.split(',');
    // process language codes ....
} } );

如果您能够通过后端生成 HTML,则可以通过简单地将语言首选项打印到页面中来完全避免使用 Ajax,例如

If you were able to generate your HTML via a back end, you could avoid using Ajax completely by simply printing the language preferences into your page, e.g.

<script>
    var prefs = <?php echo json_encode($_SERVER['HTTP_ACCEPT_LANGUAGE'])?>;
</script>

如果您无法访问服务器,但可以将脚本放到另一台服务器上,那么简单的 JSONP 服务将如下所示:

If you had no access to the server but could get a script onto another server, a simple JSONP service would look like:

<?php
$prefs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
$jsonp = 'myCallback('.json_encode($prefs).')';

header('Content-Type: application/json; charset=UTF-8', true );
header('Content-Length: '.strlen($jsonp), true );
echo $jsonp;

在你的 Ajax 中使用 jQuery 你会做类似的事情:

Using jQuery for your Ajax you'd do something like:

function myCallback( raw ){
    var prefs = raw.split(',');
    // process language codes ....
}
$.ajax( {
    url: 'http://some.domain/script.php',
    dataType: 'jsonp'
} );

国家/地区检测是另一回事.在客户端有 navigator.geolocation,但它最可能会提示您的用户获得许可,因此不利于无缝的用户体验.

Country detection is another matter. On the client side there is navigator.geolocation, but it will most likely prompt your user for permission, so no good for a seamless user experience.

要进行隐形操作,您仅限于地理 IP 检测.同理,也不要用语言来暗示国家.

To do invisibly, you're limited to geo IP detection. By the same token as above, don't use language to imply country either.

要在客户端进行国家/地区检测,您还需要后端服务来获取客户端 IP 地址并访问 IP/位置映射数据库.Maxmind 的 GeoIP2 JavaScript 客户端 似乎为您将这一切包装在一个客户端包中,所以您不会不需要您自己的服务器(尽管我确信它会使用远程 jsonp 服务).还有freegeoip.net,在注册方面可能比MaxMind更省事,而且貌似也是开源的.

To do country detection on the client side, you'll also need a back end service in order to get the client IP address and access a database of IP/location mappings. Maxmind's GeoIP2 JavaScript client appears to wrap this all up in a client-side bundle for you, so you won't need your own server (although I'm sure it will use a remote jsonp service). There's also freegeoip.net, which is probably less hassle than MaxMind in terms of signing up, and it appears to be open source too.

相关文章