简体   繁体   English

如何检测用户的语言并重定向到适合语言的网页?

[英]How can I detect the user's language and redirect to a language appropriate webpage?

I'm trying to detect the user's language settings, then redirect her based on that. 我试图检测用户的语言设置,然后根据该用户重定向。 If the user has pl as her default language setting, she should be redirected to polish.html . 如果用户将pl作为默认语言设置,则应将其重定向到polish.html If ru , then russian.html . 如果为rurussian.html Otherwise, english.html . 否则为english.html

a = navigator.language;
b = navigator.userLanguage;

language = (a && !b)? a.toLowerCase() : b;

pl = 'pl';
ru = 'ru';
en = 'en'||'us'||'au'||'bz'||'ca'||'gb'||'ie'||'jm'||'nz'||'tt'||'za';

switch (language) {
  case pl: window.location.replace('polish.html'); break;
  case ru: window.location.replace('russian.html'); break;
  case en: window.location.replace('english.html'); break;
}

In general, the above script works, except for one problem: the browser continually refreshes the page. 通常,上面的脚本有效,除了一个问题:浏览器不断刷新页面。 How can I fix this problem? 我该如何解决这个问题?

Your problem is that you are continually reloading the page, regardless of your current state. 您的问题是无论当前状态如何,您都在不断重新加载页面。 If your user's language is English and you're on english.html , there's no reason to reload the page. 如果您的用户的语言是英语,并且您使用的是english.html ,则没有理由重新加载页面。

var language = (navigator.language || navigator.userLanguage).toLowerCase(),
    // simpler way of getting the user's language (take advantage of || in JS)
    en = [ "en", "us", "au", "bz", "ca", "gb", "ie", "jm", "nz", "tt", "za" ],
    // we'll need an array of the languages associated with English
    currentPage = window.location.href.toLowerCase();

if (language == "pl" && currentPage.indexOf("polish") == -1) {
    // if the user's language is polish and the page's link doesn't contain polish
    // in it, redirect the user to polish.html
    window.location.replace("polish.html");
} else if (language == "ru" && currentPage.indexOf("russian") == -1) {
    // same concept as above
    window.location.replace("russian.html");
} else if (en.indexOf(language) > -1 && currentPage.indexOf("english") == -1) {
    // here, we're checking whether their language is in the array
    // of user languages that should default to english
    window.location.replace("english.html");
}

You can even simplify the above logic by removing en.indexOf(language) > -1 from the last else if statement. 您甚至可以通过从最后的else if语句中删除en.indexOf(language) > -1来简化上述逻辑。 This'll make the default landing page english.html . 这将使默认的登录页面为english.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM