JavaScript Cookie 读写删除操作函数详解
作者:木棉时间:2026-10-24 15:46:53浏览:440
本文提供了一套完整的 JavaScript 函数,用于处理 Cookie 的读取、设置与删除操作。代码涵盖了获取指定名称的 Cookie 值、设置带有过期时间、路径、域名和安全标志的 Cookie,以及通过设置过去时间戳来删除特定 Cookie 的方法。适用于需要手动管理浏览器本地存储的前端开发场景。
相关代码实现如下:
读取 Cookie 函数function getCookie( name )
{
var start = document.cookie.indexOf( name + "=" );
var len = start + name.length + 1;
if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
return null;
}
if ( start == -1 ) return null;
var end = document.cookie.indexOf( ';', len );
if ( end == -1 ) end = document.cookie.length;
return unescape( document.cookie.substring( len, end ) );
}
// ---------------------------------------------------- //
设置 Cookie 函数function setCookie( name, value, expires, path, domain, secure ) {
var today = new Date();
today.setTime( today.getTime() );
if ( expires ) {
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );
document.cookie = name+'='+escape( value ) +
( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
( ( path ) ? ';path=' + path : '' ) +
( ( domain ) ? ';domain=' + domain : '' ) +
( ( secure ) ? ';secure' : '' );
}
// ---------------------------------------------------- //
删除 Cookie 函数function deleteCookie( name, path, domain )
{
if ( getCookie( name ) ) document.cookie = name + '=' +
( ( path ) ? ';path=' + path + '') +
( ( domain ) ? ';domain=' + domain : '' ) +
';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}作者最新文章
JS中将数组和对象混合组装为JSON字符串
2026-11-05 16:41:42
JS运算符优先级与结合性的区别是什么?
2026-11-05 13:22:02
JS Map怎么只遍历Key或Value
2026-11-05 13:00:36
D3.js 与 ECharts 选型对比:灵活性 vs 开发效率
2026-11-05 09:45:01
为什么JS中typeof []返回object:数组类型检测误区解析
2026-11-04 19:50:47
