简体   繁体   中英

Check cookie and redirect user with jQuery?

I have a site that has a log in page for english and one for french. I am checking for a cookie on page load and if it does not exist redirects user to the english log in page. Is there a way to conditionally check if the user is trying to access a french page to redirect them to the french log in page? Right now I have the logic setup but it creates a bad loop and does not work? is this even possible with jquery?

jQuery:

function checkCookie() {
    var current_url = window.location.pathname;
    var logInCookie = _siteNS.Utils.readCookie('x-access');
   
    if (!logInCookie && current_url != '/landing.html') {
      window.location.replace('/landing.html');

    } else if (!logInCookie && current_url != '/landing-fr.html') {
      window.location.replace('/landing-fr.html');
    }
    console.log('cookie', logInCookie);
  }

Your logic is saying that (assuming there is no x-access cookie), if we are not at /landing.html , go there. (One second, heading over...) and if you are not at /landing-fr.html (No I am NOT! You just sent me to /landing.html !) then go there ... (Ok, fine, I'll go. But I was there already and you sent me away...)

Can you see the loop you are making?

Remember, every time a redirect happens, your code executes in the new page, having no recollection of ever having run before...

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