JavaScript Cookie 操作工具函数详解:读写删除与注意事项

作者:代码拾荒时间:2026-10-25 08:04:51浏览:136

本文提供了一套完整的 JavaScript Cookie 操作工具函数,涵盖 getCookie、setCookie 和 deleteCookie 方法。通过封装日期格式化与字符串解析逻辑,简化了 Cookie 的读写流程。文章同时详细说明了 Cookie 的存储限制、跨域设置及浏览器兼容性检测,帮助开发者在客户端安全高效地管理用户配置数据。

JavaScript Cookie 操作工具函数详解:读写删除与注意事项

问题:


在访问网页时,我们希望保留用户上次的偏好设置,或在不同页面间共享数据。例如,用户调整了页面字体大小后,期望下次访问时能自动应用该设置,而无需重新配置。


解决方案:


在用户进行页面设置时,将相关配置保存至 Cookie 中;下次访问时,从 Cookie 读取这些配置并应用。


参考下面的脚本:


代码如下:

 
// utility function to retrieve an expiration data in proper format;
function getExpDate(days, hours, minutes)
{ 
var expDate = new Date();
if(typeof(days) == "number" && typeof(hours) == "number" && typeof(hours) == "number")
{ 
expDate.setDate(expDate.getDate() + parseInt(days));
expDate.setHours(expDate.getHours() + parseInt(hours));
expDate.setMinutes(expDate.getMinutes() + parseInt(minutes));
return expDate.toGMTString();
} 
} 
//utility function called by getCookie()
function getCookieVal(offset)
{ 
var endstr = document.cookie.indexOf(";", offset);
if(endstr == -1)
{ 
endstr = document.cookie.length;
} 
return unescape(document.cookie.substring(offset, endstr));
} 
// primary function to retrieve cookie by name
function getCookie(name)
{ 
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while(i < clen)
{ 
var j = i + alen;
if (document.cookie.substring(i, j) == arg)
{ 
return getCookieVal(j);
} 
i = document.cookie.indexOf(" ", i) + 1;
if(i == 0) break;
} 
return;
} 
// store cookie value with optional details as needed
function setCookie(name, value, expires, path, domain, secure)
{ 
document.cookie = name + "=" + escape(value) +
((expires) ? "; expires=" + expires : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
} 
// remove the cookie by setting ancient expiration date
function deleteCookie(name,path,domain)
{ 
if(getCookie(name))
{ 
document.cookie = name + "=" +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
"; expires=Thu, 01-Jan-70 00:00:01 GMT";
} 
} 

使用 getCookie(name) 函数读取 Cookie 中保存的值,参数 name 为 Cookie 项的名称。若该 Cookie 项不存在,则返回空字符串。


使用 setCookie() 函数保存 Cookie 项的值,前两个参数分别为 Cookie 的名称和值。如需设置过期时间,需传入第三个参数,该参数应通过 getExpDate() 获取正确格式的时间字符串。


最后,使用 deleteCookie() 删除已存在的 Cookie 项。其原理是将该 Cookie 的过期时间设置为一个过去的日期,从而使其失效。


Cookie 将数据保存在客户端。页面脚本只能读取当前域和服务器的 Cookie 值;若域内包含多个服务器,需设置第五个参数以指定服务器。浏览器通常限制每服务器存储 20 个 name/value 对,每个 Cookie 项不超过 4000 个字符。实际使用中,建议单个 Cookie 项少于 2000 字符,避免在客户端保存大容量数据。


不同浏览器保存 Cookie 的方式存在差异。IE 为每个域的 Cookie 建立单独的文本文件,而 Netscape 将所有 Cookie 存储在同一个文本文件中。


注意:Cookie 存放在客户端,受浏览器设置影响,用户可能禁用 Cookie。要检测浏览器是否支持 Cookie,可使用 navigator.cookieEnabled 属性进行判断。



1

2下一页阅读全文

作者最新文章