JavaScript Cookie 读写删除操作函数详解

作者:木棉

时间:2026-10-24

浏览:439

本文提供了一套完整的 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';
}

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章