javascript.cookie

本文提供了一套JavaScript函数,用于处理浏览器Cookies。包括设置、获取、删除Cookie的方法,并且介绍了如何指定Cookie的有效期、路径、域等属性。
 
  1. // utility function to retrieve an expiration data in proper format;
  2. function getExpDate(days)
  3. {
  4.     var expDate = new Date();
  5.     if(typeof(days) == "number")
  6.     {
  7.         expDate.setDate(expDate.getDate() + parseInt(days));        
  8.     }
  9.     return expDate.toGMTString();
  10. }
  11. //utility function called by getCookie()
  12. function getCookieVal(offset)
  13. {
  14.     var endstr = document.cookie.indexOf(";", offset);
  15.     if(endstr == -1)
  16.     {
  17.         endstr = document.cookie.length;
  18.     }
  19.     return unescape(document.cookie.substring(offset, endstr));
  20. }
  21. // primary function to retrieve cookie by name
  22. function getCookie(name)
  23. {
  24.     var arg = name + "=";
  25.     var alen = arg.length;
  26.     var clen = document.cookie.length;
  27.     var i = 0;
  28.     while(i < clen)
  29.     {
  30.         var j = i + alen;
  31.         if (document.cookie.substring(i, j) == arg)
  32.         {
  33.             return getCookieVal(j);
  34.         }
  35.         i = document.cookie.indexOf(" ", i) + 1;
  36.         if(i == 0) break;
  37.     }
  38.     return null;
  39. }
  40. // store cookie value with optional details as needed
  41. function setCookie(name, value, expires, path, domain, secure)
  42. {
  43.     document.cookie = name + "=" + escape(value) +
  44.     "; expires=" + ((expires) ? expires : getExpDate(30)) +
  45.     "; path=" + ((path) ? path : "/") +
  46.     ((domain) ? "; domain=" + domain : "") +
  47.     ((secure) ? "; secure" : "");
  48. }
  49. // remove the cookie by setting ancient expiration date
  50. function deleteCookie(name,path,domain)
  51. {
  52.     if(getCookie(name))
  53.     {
  54.         document.cookie = name + "=" +
  55.         ((path) ? "; path=" + path : "") +
  56.         ((domain) ? "; domain=" + domain : "") +
  57.         "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  58.     }
  59. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值