问题
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 doesnt 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?
回答1:
Cookies are strictly a HTTP mechanism as per RFC 2109.
See this link, here, for the chrome "bug" report of this.
You can, however, run chrome with the flag --enable-file-cookies to allow file:/// cookies
To run chrome with experimental / developer flags have a look here for instructions
It appears that the --enable-file-cookies flag has been removed from all platforms that chrome runs on except Android.
You can read more about it here and here.
With this, it appears that there is no way to store cookies under a file:/// URL structure, The best way to go around this would be to run a small server locally when developing. Here's a good list of scripts that can run a local HTTP server from the command line. link
来源:https://stackoverflow.com/questions/47417471/creating-cookies-on-file-url-evidence-it-is-being-created-but-not-showing