简体   繁体   English

给cookie添加条件check function不会造成死循环

[英]Add condition to cookie check function without causing infinite loop

I have a web page that checks for a cookie on page load and if the cookie does not exist the user is redirected to a certain log in page based on conditions.我有一个 web 页面,它在页面加载时检查 cookie,如果 cookie 不存在,则根据条件将用户重定向到某个登录页面。 I am trying to add another condition to the cookie check but it is creating an infinite loop.我正在尝试向 cookie 检查添加另一个条件,但它正在创建一个无限循环。 Is there a way to allow another condition?有没有办法允许另一个条件?

function checkCookie() {
    var current_url = window.location.pathname;
    var logInCookie = _siteNS.Utils.readCookie('x-access');

    if (!logInCookie) {
      if (
        window.location.toString().includes('-fr') &&
        current_url != '/landing-fr.html'
      ) {
        window.location.replace('/landing-fr.html');
      } else if (
        window.location.href.indexOf('-fr') === -1 &&
        current_url != '/landing.html'
      ) {
        window.location.replace('/landing.html');
      } else if (
        window.location.href.indexOf('-fr') === -1 &&  *=== This is creating infinite loop===*
        current_url === '/Important_Safety_Information.html'
      ) {
        window.location.replace('/Important_Safety_Information.html');
      }
    }
  }

The problem is that you're redirecting the user back to the page they are already on.问题是您将用户重定向回他们已经在的页面。 When the user loads that same page, it's going to invoke that same logic again and redirect the user again... to the same page.当用户加载同一页面时,它将再次调用相同的逻辑并再次将用户重定向到同一页面。

From a comment on the question above:来自对上述问题的评论:

What I want to do is if the user goes to '/Important_Safety_Information.html' stay there and do not redirect我想要做的是,如果用户转到“/Important_Safety_Information.html”,请留在那里并且不要重定向

If you don't want to redirect the user then... don't redirect the user.如果您不想重定向用户,那么...不要重定向用户。 Just remove that last else if block entirely since you don't want to perform that operation.完全删除最后一个else if块,因为您不想执行该操作。 Or, at worst, if you need to include this condition in an ongoing list of conditions then simply keep the block empty:或者,在最坏的情况下,如果您需要将此条件包含在正在进行的条件列表中,则只需将块留空:

else if (
  window.location.href.indexOf('-fr') === -1 &&
  current_url === '/Important_Safety_Information.html'
) { /* do nothing */ }

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

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