test
的cookie并将其值设置为1
?test
的cookie并将其值设置为1
?相较于之前的答案,我使用以下方法来减少操作次数。
function setCookie(name, value, expiry) {
let d = new Date();
d.setTime(d.getTime() + (expiry*86400000));
document.cookie = name + "=" + value + ";" + "expires=" + d.toUTCString() + ";path=/";
}
function getCookie(name) {
let cookie = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
return cookie ? cookie[2] : null;
}
function eatCookie(name) {
setCookie(name, "", -1);
}
Cookies最初由Netscape发明,用于为Web服务器和浏览器提供“内存”。HTTP协议安排将网页传输到您的浏览器并将浏览器请求页面发送到服务器,是无状态的,这意味着一旦服务器向请求页面的浏览器发送页面,它不会记住任何事情。因此,如果您第二次、第三次、第一百次或第一百万次访问同一个网页,服务器仍然认为这是您第一次访问。
这可能会带来许多麻烦。服务器无法记住您在访问受保护页面时是否进行了身份验证,无法记住您的用户偏好,也无法记住其他任何信息。自从个性化被发明以来,这就成为了一个主要问题。
Cookies被发明来解决这个问题。有其他解决方法,但cookies易于维护且非常灵活。
Cookie只是一个存储在浏览器中的小型文本文件。它包含一些数据:
要使用Javascript设置或取消cookie,可以执行以下操作:
// Cookies
function createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(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;
}
function setCookie(name, days) {
createCookie(name, name, days);
}
function unsetCookie(name) {
createCookie(name, "", -1);
}
setCookie("demo", 1); // to set new cookie
readCookie("demo"); // to retrive data from cookie
unsetCookie("demo"); // will unset that cookie
如何使用它?
//To set a cookie
$.cookie('the_cookie', 'the_value');
//Create expiring cookie, 7 days from then:
$.cookie('the_cookie', 'the_value', { expires: 7 });
//Create expiring cookie, valid across entire page:
$.cookie('the_cookie', 'the_value', { expires: 7, path: '/' });
//Read cookie
$.cookie('the_cookie'); // => 'the_value'
$.cookie('not_existing'); // => null
//Delete cookie by passing null as value:
$.cookie('the_cookie', null);
// Creating cookie with all availabl options
$.cookie('myCookie2', 'myValue2', { expires: 7, path: '/', domain: 'example.com',
secure: true, raw: true });
可用选项:
expires: 定义 cookie 的生命周期。值可以是数字(将被解释为从创建时间开始的天数)或日期对象。如果省略,则 cookie 是会话 cookie。
path: 定义 cookie 有效的路径。默认情况下,cookie 的路径是创建 cookie 的页面的路径(标准浏览器行为)。如果您想使其在整个页面上可用,例如使用 path: '/'。
domain: 创建 cookie 的页面的域名。
secure: 默认值:false。如果为 true,则 cookie 传输需要安全协议 (https)。
raw: 默认情况下,在创建/读取时对 cookie 进行编码/解码,使用 encodeURIComponent/decodeURIComponent。通过设置 raw: true 来关闭。
以下是如何用一行JavaScript读取cookie。我在Guilherme Rodrigues的博客文章中找到了答案:
('; '+document.cookie).split('; '+key+'=').pop().split(';').shift()
key
的cookie,简洁明了。编辑:如果没有设置天数,还添加了“永不过期”的选项
function setCookie(key, value, days) {
var expires = new Date();
if (days) {
expires.setTime(expires.getTime() + (days * 24 * 60 * 60 * 1000));
document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
} else {
document.cookie = key + '=' + value + ';expires=Fri, 30 Dec 9999 23:59:59 GMT;';
}
}
function getCookie(key) {
var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
return keyValue ? keyValue[2] : null;
}
setCookie('myData', 1, 30); // myData=1 for 30 days.
setCookie('myData', 1); // myData=1 'forever' (until the year 9999)
我知道已经有很多答案了,但这里有一个非常漂亮地使用set
、get
和delete
的全局引用:
window.cookieMonster = window.cookieMonster ||
{
// https://dev59.com/_2035IYBdhLWcg3wE7xs#25490531
get: function (cookieName) {
var b = document.cookie.match('(^|;)\\s*' + cookieName + '\\s*=\\s*([^;]+)');
return b ? b.pop() : '';
},
delete: function (name) {
document.cookie = '{0}=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;'
.replace('{0}', name);
},
set: function (name, value) {
document.cookie =
'{0}={1};expires=Fri, 31 Dec 9999 23:59:59 GMT;path=/;SameSite=Lax'
.replace('{0}', name)
.replace('{1}', value);
}
};
请注意,获取Cookie的正则表达式是从另一个城堡问题的答案中取得的。
让我们来测试一下:
cookieMonster.set('chocolate', 'yes please');
cookieMonster.set('sugar', 'that too');
console.log(cookieMonster.get('chocolate'));
console.log(document.cookie);
cookieMonster.delete('chocolate');
console.log(cookieMonster.get('chocolate'));
console.log(document.cookie);
yes please
chocolate=yes please; sugar=that too
sugar=that too
www.some.sub.domain.com
、.some.sub.domain.com
、.sub.domain.com
等)。document.cookie.replace(/(?<=^|;).+?(?=\=|;|$)/g, name => location.hostname.split('.').reverse().reduce(domain => (domain=domain.replace(/^\.?[^.]+/, ''),document.cookie=`${name}=;max-age=0;path=/;domain=${domain}`,domain), location.hostname));
这是单行代码的可读版本:
document.cookie.replace(
/(?<=^|;).+?(?=\=|;|$)/g,
name => location.hostname
.split(/\.(?=[^\.]+\.)/)
.reduceRight((acc, val, i, arr) => i ? arr[i]='.'+val+acc : (arr[i]='', arr), '')
.map(domain => document.cookie=`${name}=;max-age=0;path=/;domain=${domain}`)
);