简体   繁体   中英

Redirect a user to a URL from input, store in cookie

I'm working on a project in which the user is sent to the directory name they entered in an input, like so:

function sendanswer(e) {
if (e.keyCode === 13) {
    e.preventDefault();
    var answer = document.answerarea.input.value;
    if (answer) {window.location.href = answer;}
}
}

document.answerarea.input.onkeypress = sendanswer;

This works fine. But now I want for the user to be automatically redirected to the directory they specified every time they visit the page, BUT only if they didn't recieve a 404 error after navigating to the directory. I imagine this would be accomplished by erasing the cookie when the 404 page is visited.

But how would the redirecting-to-cookie process work?

When you get input from use set a cookie using this code:

function sendanswer(e) {
  if (e.keyCode === 13) {
      e.preventDefault();
      var answer = document.answerarea.input.value;
      if (answer) {
         window.location.href = answer;
         //SET COOKIE WITH NAME redirectPath
         document.cookie="redirectPath="+ answer;
      }
  }
}

Now on your home page (the page which user gets on visiting your site) add following call on-page load:

window.onload=function(){
    var kuki = "redirectPath=";//NAME OF COOKIE WE SET
    var cookies = document.cookie.split(';');
    for(var i=0;i < cookies.length;i++) {
        var c = cookies[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(kuki) == 0){
           var path = c.substring(kuki.length,c.length);
           //MOVE USER TO STORED PATH
           document.location.href=path;
        }
    }   

}

A better approach will be to read cookie on server-side and redirect user to their favourite folder from there.

For more reference check this answer.

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