使用JavaScript获取和设置Cookies感觉有点奇怪,像这样:
设置:document.cookie = "<key>=<value>[;expires=<utc_expires>[;path=<path>]]";
获取:解析 document.cookie
我在 W3C.org Cookies 上找到了这个获取和设置函数。
是否有更加优雅/简单的方法来完成这个操作?
使用JavaScript获取和设置Cookies感觉有点奇怪,像这样:
设置:document.cookie = "<key>=<value>[;expires=<utc_expires>[;path=<path>]]";
获取:解析 document.cookie
我在 W3C.org Cookies 上找到了这个获取和设置函数。
是否有更加优雅/简单的方法来完成这个操作?
setCookie()
和getCookie()
。setCookie('myName','value', 3);
function setCookie(name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
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, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
注意: 来源于quirksmode。如果您想更多地了解cookie,请查看文档。
`docCookies.setItem(name, value);` 这可能是最优雅的实现方式。
- user3596335document.cookie.split(';').map(c => c.trimLeft())
代替 while
循环。 - David FerreiraES6的做法是:
const setCookie = (cookieKey, cookieValue, expirationDays) => {
let expiryDate = '';
if (expirationDays) {
const date = new Date();
date.setTime(`${date.getTime()}${(expirationDays || 30 * 24 * 60 * 60 * 1000)}`);
expiryDate = `; expiryDate=" ${date.toUTCString()}`;
}
document.cookie = `${cookieKey}=${cookieValue || ''}${expiryDate}; path=/`;
}
const getCookie = (cookieKey) => {
let cookieName = `${cookieKey}=`;
let cookieArray = document.cookie.split(';');
for (let cookie of cookieArray) {
while (cookie.charAt(0) == ' ') {
cookie = cookie.substring(1, cookie.length);
}
if (cookie.indexOf(cookieName) == 0) {
return cookie.substring(cookieName.length, cookie.length);
}
}
}