I have some code that creates cookies. It creates two different user groups, checks for what group the users cookie is and does something based on it.
The code is being developed on a local machine so it is accessed through a file:/// URL
It looks like this:
function cookieCreation() {
var groupId = Math.floor(Math.random() * 2) + 1;
var expDate = new Date(new Date().getTime()+60*60*1000*24).toGMTString()
document.cookie = "userGroup_" + groupId + ";" + "expires=" + expDate +";path=/";
}
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 "";
}
function cookieBasedPush() {
cookieCreation();
var currentCookie = getCookie("userGroup_1");
if (currentCookie == null) {
console.log("User Group 2");
} else {
console.log("User Group 1");
}
}
window.onload = cookieBasedPush;
A cookie looks like it is being created because I can see "User Group 1" is being console logged. However, when I run document.cookie, I get nothing.
I searched and found Setting Cookies using JavaScript in a local html file and based on this answer, suggests that cookies can't be created in a file:/// URL.
That is what confuses me and doesn't make any sense - If that is the case, then why am I getting a successful console.log of the user group 1 cookie creation? Why is document.cookie blank when run in console? Is my logic not right in code?