【发布时间】:2017-11-21 16:03:58
【问题描述】:
我有一些创建 cookie 的代码。它创建了两个不同的用户组,检查用户 cookie 是什么组,并根据它做一些事情。
代码正在本地机器上开发,因此可以通过 file:/// URL 访问它
看起来像这样:
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;
一个 cookie 看起来像 它正在被创建,因为我可以看到“用户组 1”正在被控制台记录。但是,当我运行 document.cookie 时,我什么也得不到。
我搜索并找到Setting Cookies using JavaScript in a local html file 并基于此答案,建议无法在 file:/// URL 中创建 cookie。
这让我感到困惑并且没有任何意义 - 如果是这种情况,那么为什么我会成功获得用户组 1 cookie 创建的 console.log?为什么在控制台中运行时 document.cookie 为空白?我的逻辑是不是代码不对?
【问题讨论】:
标签: javascript file cookies