[英]How can I detect the user's language and redirect to a language appropriate webpage?
我試圖檢測用戶的語言設置,然后根據該用戶重定向。 如果用戶將pl
作為默認語言設置,則應將其重定向到polish.html
。 如果為ru
, russian.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;
}
通常,上面的腳本有效,除了一個問題:瀏覽器不斷刷新頁面。 我該如何解決這個問題?
您的問題是無論當前狀態如何,您都在不斷重新加載頁面。 如果您的用戶的語言是英語,並且您使用的是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");
}
您甚至可以通過從最后的else if
語句中刪除en.indexOf(language) > -1
來簡化上述邏輯。 這將使默認的登錄頁面為english.html
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.