JavaScript原生Cookie封装工具:原理、实现与使用指南

作者:闭包旅人

时间:2026-10-28

浏览:543

本文详细介绍如何使用原生JavaScript封装一个轻量级的Cookie操作工具类。通过对象化封装,提供get、set、remove、clear等常用方法,支持maxAge、path、domain等参数配置。文章包含完整源码解析、使用示例及冲突解决机制,帮助开发者简化Cookie操作,提升代码复用性与兼容性。

文章目录

前言与背景

一、前言

以往操作Cookie时,通常直接通过document.cookie进行读写,虽然兼容性良好,但过程繁琐。鉴于个人偏好封装工具类,因此针对Cookie操作封装了一个专用工具。长期以来,我更倾向于编写代码而非撰写文字总结或零散笔记,此次尝试改变这一习惯。

封装思路与方法设计

二、思路

(1)如何封装,封装成啥样

封装方式:采用原生JavaScript编写工具类,确保其通用性。基于document.cookie进行封装是最优方案,所有操作均以此为基础。

封装形态:设计为对象形式,并支持getter与setter方法调用。

(2)封装哪些方法

包含get()、set(name, value, opts)、remove(name)、clear()、getCookies()等方法,足以满足日常Cookie操作需求。

Cookie原理与核心实现

三、行动

(1)了解Cookie,Cookie实质为HTTP Cookie,在客户端表现为document.cookie对象。更多细节可参考下方代码及注释。

(2)上代码:代码直观易懂,可与项目代码一起压缩。重点在于开头的注释说明。

代码如下:

/*
* HTTP Cookie:存储会话信息
* 名称和值传送时必须是经过RUL编码的
* cookie绑定在指定的域名下,非本域无法共享cookie,但是可以是在主站共享cookie给子站
* cookie有一些限制:比如IE6 & IE6- 限定在20个;IE7 50个;Opear 30个...所以一般会根据【必须】需求才设定cookie
* cookie的名称不分大小写;同时建议将cookie URL编码;路径是区分cookie在不同情况下传递的好方式;带安全标志cookie
* 在SSL情况下发送到服务器端,http则不会。建议针对cookie设置expires、domain、 path;每个cookie小于4KB
 * */
//对cookie的封装,采取getter、setter方式
(function(global){
//获取cookie对象,以对象表示
function getCookiesObj(){
var cookies = {};
if(document.cookie){
var objs = document.cookie.split('; ');
for(var i in objs){
var index = objs[i].indexOf('='),
name = objs[i].substr(0, index),
value = objs[i].substr(index + 1, objs[i].length);
cookies[name] = value;
            }
        }
return cookies;
    }
//设置cookie
function set(name, value, opts){
//opts maxAge, path, domain, secure
if(name && value){
var cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value);
//可选参数
if(opts){
if(opts.maxAge){
cookie += '; max-age=' + opts.maxAge;
                }
if(opts.path){
cookie += '; path=' + opts.path;
                }
if(opts.domain){
cookie += '; domain=' + opts.domain;
                }
if(opts.secure){
cookie += '; secure';
                }
            }
document.cookie = cookie;
return cookie;
}else{
return '';
        }
    }
//获取cookie
function get(name){
return decodeURIComponent(getCookiesObj()[name]) || null;
    }
//清除某个cookie
function remove(name){
if(getCookiesObj()[name]){
document.cookie = name + '=; max-age=0';
        }
    }
//清除所有cookie
function clear(){
var cookies = getCookiesObj();
for(var key in cookies){
document.cookie = key + '=; max-age=0';
        }
    }
//获取所有cookies
function getCookies(name){
return getCookiesObj();
    }
//解决冲突
function noConflict(name){
if(name && typeof name === 'string'){
if(name && window['cookie']){
window[name] = window['cookie'];
delete window['cookie'];
return window[name];
            }
}else{
return window['cookie'];
delete window['cookie'];
        }
    }
global['cookie'] = {
'getCookies': getCookies,
'set': set,
'get': get,
'remove': remove,
'clear': clear,
'noConflict': noConflict
    };
})(window);

使用示例与冲突解决

(3)example

代码如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>cookie example</title>
</head>
<body>
<script type="text/javascript" src="cookie.js" ></script>
<script type="text/javascript">
console.log('----------cookie对象-------------');
console.log(cookie);
console.log('----------对象-------------');
console.log(cookie.getCookies());
console.log('----------设置cookie-------------');
console.log(cookie.set('name', 'wlh'));
console.log('----------设置cookie 123-------------');
console.log(cookie.set('name', 'wlh123'));
console.log('----------设置cookie age-------------');
console.log(cookie.set('age', 20));
console.log('----------获取cookie-------------');
console.log(cookie.get('name'));
console.log('----------获取所有-------------');
console.log(cookie.getCookies());
console.log('----------清除age-------------');
console.log(cookie.remove('age'));
console.log('----------获取所有-------------');
console.log(cookie.getCookies());
console.log('----------清除所有-------------');
console.log(cookie.clear());
console.log('----------获取所有-------------');
console.log(cookie.getCookies());
console.log('----------解决冲突-------------');
var $Cookie = cookie.noConflict(true /*a new name of cookie*/);
console.log($Cookie);
console.log('----------使用新的命名-------------');
console.log($Cookie.getCookies());
</script>
</body>
</html>

(4)代码地址:https://github.com/vczero/cookie

实用工具推荐

电子包浆

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

使用 ›
图片压缩

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

使用 ›
相关文章