Document.cookie Document 属性 cookie 允许您读取和写入与文档关联的 cookie。它充当 cookie 实际值的 getter 和 setter。
var c = 'Yash' + '=' + 'Yash-777';
document.cookie = c; // Set the value: "Yash=Yash-777"
document.cookie // Get the value:"Yash=Yash-777"
来自 Google GWT 项目Cookies.java
类的原生代码。我准备了以下函数来对 Cookie 执行操作。
将所有 cookie 列表作为 JSON 对象获取的函数。
var uriEncoding = false;
function loadCookiesList() {
var json = new Object();
if (typeof document === 'undefined') {
return json;
}
var docCookie = document.cookie;
if (docCookie && docCookie != '') {
var crumbs = docCookie.split('; ');
for (var i = crumbs.length - 1; i >= 0; --i) {
var name, value;
var eqIdx = crumbs[i].indexOf('=');
if (eqIdx == -1) {
name = crumbs[i];
value = '';
} else {
name = crumbs[i].substring(0, eqIdx);
value = crumbs[i].substring(eqIdx + 1);
}
if (uriEncoding) {
try {
name = decodeURIComponent(name);
} catch (e) {
// ignore error, keep undecoded name
}
try {
value = decodeURIComponent(value);
} catch (e) {
// ignore error, keep undecoded value
}
}
json[name] = value;
}
}
return json;
}
设置和获取具有特定名称的 Cookie。
function getCookieValue(name) {
var json = loadCookiesList();
return json[name];
}
function setCookie(name, value, expires, domain, path, isSecure) {
var c = name + '=' + value;
if ( expires != null) {
if (typeof expires === 'number') {
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now
var timeInMs = Date.now();
if (expires > timeInMs ) {
console.log("Seting Cookie with provided expire time.");
c += ';expires=' + (new Date(expires)).toGMTString();
} else if (expires < timeInMs) {
console.log("Seting Cookie with Old expire time, which is in Expired State.");
timeInMs = new Date(timeInMs + 1000 * expires);
c += ';expires=' + (new Date(timeInMs)).toGMTString();
}
} else if (expires instanceof window.Date) {
c += ';expires=' + expires.toGMTString();
}
}
if (domain != null && typeof domain == 'string')
c += ';domain=' + domain;
if (path != null && typeof path == 'string')
c += ';path=' + path;
if (isSecure != null && typeof path == 'boolean')
c += ';secure';
if (uriEncoding) {
encodeURIComponent(String(name))
.replace(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent)
.replace(/[\(\)]/g, escape);
encodeURIComponent(String(value))
.replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g, decodeURIComponent);
}
document.cookie = c;
}
function removeCookie(name) {
document.cookie = name + "=;expires=Fri, 02-Jan-1970 00:00:00 GMT";
}
function removeCookie(name, path) {
document.cookie = name + "=;path=" + path + ";expires=Fri, 02-Jan-1970 00:00:00 GMT";
}
检查 cookie 名称是否有效:不能包含'=', ';', ',', or whitespace
. 不能以 开头$
。
function isValidCookieName(name) {
if (uriEncoding) {
// check not necessary
return true;
} else if (name.includes("=") || name.includes(";") || name.includes(",") || name.startsWith("$") || spacesCheck(name) ) {
return false;
} else {
return true;
}
}
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test
function spacesCheck(name) {
var whitespace = new RegExp('.*\\s+.*');
var result = whitespace.test(name);
console.log("Name:isContainSpace = ", name, ":", result);
return result;
}
检查上述功能的测试步骤:
setCookie("yash1", "Yash-777");
setCookie("yash2", "Yash-Date.now()", Date.now() + 1000 * 30);
setCookie("yash3", "Yash-Sec-Feature", 30);
setCookie("yash4", "Yash-Date", new Date('November 30, 2020 23:15:30'));
getCookieValue("yash4"); // Yash-Date
getCookieValue("unknownkey"); // undefined
var t1 = "Yash", t2 = "Y ash", t3 = "Yash\n";
spacesCheck(t1); // False
spacesCheck(t2); // True
spacesCheck(t3); // True