cookie的特点
1.只能使用文本
2 单条存储有大小限制 4KB
3 数量限制(一般浏览器,限制大概在50条左右)
4 读取有域名限制 不可跨域读取,只能由来自 写入cookie的 同一域名 的网页可进行读取。
5 时效限制 每个cookie都有时效,最短的有效期是,会话级别:就是当浏览器关闭,那么cookie立即销毁
JavaScript 可以用 document.cookie 属性创建修改、读取、删除 cookie。
1、通过 JavaScript,可以这样创建修改 cookie:
document.cookie = "username=xiaobai";
2、添加有效日期(UTC 时间)。默认情况下,在浏览器关闭时会删除 cookie:
cont d = new Date()
document.cookie = "username=xiaobai;expires=" + d;
3、通过 path 参数,您可以告诉浏览器 cookie 属于什么路径。默认情况下,cookie 属于当前页:
cont d = new Date()
document.cookie = "username=xiaobai;expires=" + d + ";path=/";
4、通过 JavaScript,可以这样读取 cookies:
var ck = document.cookie
5、通过 JavaScript 删除 cookie:
删除 cookie 时不必指定 cookie 值, 直接把 expires 参数设置为过去的日期即可:
document.cookie = "username=;expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/";
练习
设置cookie函数
function setCookie (cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime + (exdays * 24 * 60 * 60 * 1000))
var expires = "expires" + d.toUTCString();
document.cookie = cname + "=" cvalue + ";" + expires + ";path=/"
}
获取 cookie 的函数
function getCookie (cname) {
var name = cname + "=";
var decodeCookie = decodeURIComponent(document.cookie);
var ca = decodeCookie.split(";");
for (let 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 "";
}
检测 cookie 的函数
function checkCookie() {
var username = getCookie("username");
if (username != "") {
alert("Welcome again " + username);
} else {
username = prompt("Please enter your name:", "");
if (username != "" && username != null) {
setCookie("username", username, 365);
}
}
}