简体   繁体   中英

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. I am trying to add another condition to the cookie check but it is creating an infinite loop. 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

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. 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 */ }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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