1 var CookieUtil = {
2 get: function(name) {
3 var cookieName = encodeURIComponent(name) + "=",
4 cookieStart = document.cookie.indexOf(cookieName),
5 cookieValue = null;
6 if(cookieStart > -1) {
7 var cookieEnd = document.cookie.indexOf(";", cookieStart);
8 if(cookieEnd == -1) {
9 cookieEnd = document.cookie.length;
10 }
11 cookieValue = decodeURIComponent(document.getCookie.substring(cookieStart + cookieName.length, cookieEnd));
12 }
13 return cookieValue;
14 },
15 set: function(name, value, expires, path, domain, secure) {
16 var cookieText = encodeURIComponent(name) + "=" +
17 encodeURIComponent(value);
18 if(expires instanceof Date) {
19 cookieText += "; expires=" + expires.toGMTString();
20 }
21 if(path) {
22 cookieText += "; path=" + path;
23 }
24 if(domain) {
25 cookieText += "; domain=" + domain;
26 }
27 if(secure) {
28 cookieText += "; secure";
29 }
30 document.cookie = cookieText;
31 },
32 unset: function(name, path, domain, secure) {
33 this.set(name, "", new Date(0), path, domain, secure);
34 }
35 };
//设置一个 cookie
CookieUtil.set("name", "wolfSoul");
//读取 cookie 的值
alert(CookieUtil.get("name")); // "wolfSoul"
//删除 cookie
CookieUtil.unset("name");
cookie有较高的扩展性和可用性,但也有其缺点:
首先:每个域的 cookie 总数是有限的,不过浏览器之间各有不同。如下所示
当超过单个域名限制之后还要再设置 cookie,浏览器就会清除以前设置的 cookie。IE 和 Opera 会删 除最近最少使用过的(LRU,Least Recently Used)cookie,腾出空间给新设置的 cookie。Firefox 看上去 好像是随机决定要清除哪个 cookie,所以考虑 cookie 限制非常重要,以免出现不可预期的后果。
其次:要考虑安全性问题。如果cookie被人拦截了,拦截者就可以取得所有的session信息。即使加密也也没有用,而拦截者也并不需要知道cookie的意义,这会引起安全方面的问题。