繁体   English   中英

基于浏览器语言的 JS 重定向 if ... else' 语句无限循环

[英]JS Redirect based on browser language if ... else' statement loops infinitely

我已经编写了一小段代码来根据浏览器语言进行重定向,但是如果我使用原始 URL,代码的“else”部分将无限循环。

我已经测试过它,如果我重定向到不同的 URL,它就像一个魅力,所以我假设它与尝试将它重定向回原始 URL 有关,但不知道如何阻止它。 Break/Continue 和 console.log 有效,但前两个是非法的,显然我不能离开 console.log :如果第一个条件为假,SI 需要告诉 if/else 语句基本上停止或“停留在页面上” .

有人能告诉我如何解决这个问题,以便如果浏览器语言设置为法语,重定向 ELSE 会留在原始 URL 上吗?

<!-- language redirect -->
    <script>
        userLang = navigator.language || navigator.userLanguage;

    if (userLang == "fr") {
        window.location.href = "http://www.website.com/fr";

    }
    else {
        console.log('null'); *** THIS WORKS but is not right

window.location.href = "http://www.website.com"; *** THIS DOESN'T WORK gets stuck in a loading loop infinitely

window.location.href="http://www.someotherwebsite.com"; ***THIS WORKS but doesn't achieve my purpose
}
</script>

如果浏览器语言是法语,则重定向到法语网站(子目录)ELSE 什么都不做,停留在英语网站上。

由于此脚本只会在英文页面中实现,因此您无需为 else 语句传递任何内容。

userLang = navigator.language || navigator.userLanguage;

if (userLang == "fr") {
    window.location.href = "http://www.website.com/fr";
}

对于法语页面,您只需将“fr”更改为“en”。

当您将 url 分配给window.location.href属性时,即使将指定的 url 设置为您当前所在的 url,也会加载该 url。 如果语言不是法语,这会导致您的浏览器不断重新加载您的网站。

来自MDN

每当为 location 对象分配新值时,将使用 URL 加载文档,就像使用修改后的 URL 调用 location.assign() 一样。 请注意,安全设置(如 CORS)可能会阻止这种情况有效发生。

为了解决您的问题,当您已经在用户语言的正确页面上时,您不应设置window.location.href属性。

这只是一个逻辑问题。 如果它已经在那里,为什么要重定向到一个 url? 只需额外检查一下,它是否已经在正确的 url 中,如下所示

<script>
        userLang = navigator.language || navigator.userLanguage;

    if (userLang == "fr" && window.location.href!= "http://www.website.com/fr") {

        window.location.href = "http://www.website.com/fr";

    }
    else {

       if(window.location.href != "http://www.website.com") {
             window.location.href = "http://www.website.com";
       }

    }

</script>

暂无
暂无

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

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