0

I have a home page with a choice of 2 links. When one of those links is clicked I want to create a cookie so that all other internal pages remember this choice.

How do I set a cookie on one page and read the same cookie on different pages?

This is what I have:

// Home page on click event function setRed() { document.cookie = "color=red; max-age=" + 60 * 60 * 24 * 365; // 60 seconds to a minute, 60 minutes to an hour, 24 hours to a day, and 365 days. }; //Internal Page Check window.onload = checkCookie(); function checkCookie() { if (document.cookie.indexOf("color") == "red") { document.body.id = "red"; } else { document.body.id = "blue"; }; }; 
1

2 Answers 2

2

Please check out this stackoverflow question.

Basically, when you say document.cookie make sure to add this to the end of it:

;path=/ 

Then call checkCookie()

This basically tells the browser to let the cookie be accessed anywhere across the site. However, as far as I know, if your two pages are hosted on different domains it is impossible for both of them to access the same cookie (due to security reasons.)

Also, the function you use to get the cookie looks incorrect. From w3schools:

function getCookie(cname) { var name = cname + "="; var ca = document.cookie.split(';'); for(var i=0; i<ca.length; i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1); if (c.indexOf(name) == 0) return c.substring(name.length,c.length); } return ""; } 

You could then use this function in your checkCookie() function:

function checkCookie() { if (getCookie("color") == "red") { document.body.id = "red"; } else { document.body.id = "blue"; }; }; 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, works great now. Can you explain why the getCookie function was incorrect? I leaned that method on another stack overflow question and it did work for a single page setup, but not here...
@user500665 Try logging the value of document.cookie. It's a string, so if memory serves me right then it doesn't contain the function indexOf.
1

Try adding path to your cookie so that all page within your site can access it.

// Home page on click event function setRed() { // 60 seconds to a minute, 60 minutes to an hour, 24 hours to a day, and 365 days. document.cookie = "color=red; max-age=" + 60 * 60 * 24 * 365 +"; path=/"; }; //Internal Page Check window.onload = checkCookie(); function checkCookie() { if (document.cookie.indexOf("color") == "red") { document.body.id = "red"; } else { document.body.id = "blue"; }; }; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.