[英]How to stop infinite loop of javascript while detecting browser language
My objective is to detect the user's language and redirect them to either a French page or English, with English being the default. 我的目标是检测用户的语言,然后将其重定向到法语页面或英语(默认为英语)。 This works if I put the code on the French page only and try to open the French page, this auto detects and loads the English.
如果我仅将代码放在法语页面上并尝试打开法语页面,则此方法会自动检测并加载英语。 If I have the code on both then it just gets stuck in an infinite loop.
如果我在两者上都有代码,那么它将陷入无限循环。 Any help would be greatly appreciated.
任何帮助将不胜感激。 Here is the code.
这是代码。
<script language="javascript">
var langcodes=new Array("en", "fr", "default") ;
var langredirects=new Array("http://defaulten.asp",
"http://default-fr.asp",
"http://default.asp");
var languageinfo=navigator.language? navigator.language : navigator.userLanguage ;
var gotodefault=1 ;
function redirectpage(dest){
if (window.location.replace)
window.location.replace(dest)
else
window.location=dest
}
for (i=0;i<langcodes.length-1;i++){
if (languageinfo.substr(0,2)==langcodes[i]){
redirectpage(langredirects[i])
gotodefault=0
break
}
}
if (gotodefault)
redirectpage(langredirects[langcodes.length-1])
</script>
You need to make sure you don't re-direct if you are already on the correct page eg 如果您已经在正确的页面上,则需要确保不重定向,例如
if (languageinfo.substr(0,2)==langcodes[i]) {
gotodefault = 0;
var redirPage = langredirects[i];
if (redirPage != document.URL)
redirectpage(redirPage);
break
}
Also, if en
is the default I wouldn't have a specific page for that ie defaulten.asp
. 另外,如果
en
是默认值,则没有该页面的特定页面,即defaulten.asp
。 I would only provide language specific pages ie default-fr.asp
/ default-us.asp
, if you followed this approach your code would be even simpler eg 我只提供特定语言的页面,即
default-fr.asp
/ default-us.asp
,如果您遵循这种方法,您的代码将更加简单,例如
var languageinfo = navigator.language ? navigator.language : navigator.userLanguage;
languageinfo = languageinfo == "en" ? "" : languageinfo;
var langUrl = sprintf("http://default%s.asp", languageinfo);
if (document.URL != langUrl)
redirectpage(langUrl);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.