Reputation: 87
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?
Upvotes: 2
Views: 1005
Reputation: 40497
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.
Upvotes: 2