jQuery-Cookie 扩展插件开发:自定义功能实现指南
你是否在开发网站时遇到过 cookie 操作繁琐、功能单一的问题?是否需要更灵活的 cookie 管理方案来满足复杂业务需求?本文将带你从零开始扩展 jQuery-Cookie 插件,实现自定义过期时间计算、批量操作、数据加密等实用功能,让 cookie 管理变得简单高效。读完本文后,你将掌握插件扩展的核心方法,能够根据实际需求定制专属的 cookie 操作工具。
项目基础认知
jQuery-Cookie 是一个轻量级的 jQuery 插件,用于简化浏览器 cookie 的读取、写入和删除操作。该项目已迁移至 js-cookie/js-cookie,其中定义了 $.cookie 和 $.removeCookie 两个主要方法,以及相关的配置选项和工具函数。
核心文件结构
src/jquery.cookie.js 的代码结构清晰,主要包含以下几个部分:
- 模块定义:采用 UMD (Universal Module Definition) 模式,支持 AMD、CommonJS 和全局变量三种引入方式。
- 编码/解码函数:
encode、decode、stringifyCookieValue和parseCookieValue用于处理 cookie 值的编码和解码。 - 读取/写入方法:
$.cookie方法根据参数数量和类型,实现 cookie 的读取、写入和删除功能。 - 默认配置:
config.defaults对象存储默认的 cookie 选项,如过期时间、路径、域名等。 - 辅助方法:
$.removeCookie方法用于删除 cookie,内部调用$.cookie方法并设置过期时间为 -1。
扩展开发环境准备
在开始扩展之前,需要准备好开发环境。首先,从 GitCode 仓库克隆项目代码:
git clone https://gitcode.com/gh_mirrors/jq/jquery-cookie.git
cd jquery-cookie
项目的目录结构如下:
gh_mirrors/jq/jquery-cookie/
├── CHANGELOG.md
├── CONTRIBUTING.md
├── Gruntfile.js
├── MIT-LICENSE.txt
├── README.md
├── bower.json
├── component.json
├── cookie.jquery.json
├── package.json
├── src/
│ └── jquery.cookie.js
└── test/
├── index.html
├── malformed_cookie.html
└── tests.js
其中,test/index.html 和 test/tests.js 提供了基础的测试用例,可用于验证扩展功能的正确性。建议使用浏览器打开 test/index.html 查看现有测试结果,确保基础功能正常。
自定义功能实现
1. 自定义过期时间计算
默认情况下,$.cookie 方法的 expires 选项接受天数作为参数。我们可以扩展一个 expiresHours 选项,支持按小时设置过期时间。
打开 src/jquery.cookie.js,找到处理过期时间的代码块(第 62-65 行):
if (typeof options.expires === 'number') {
var days = options.expires, t = options.expires = new Date();
t.setMilliseconds(t.getMilliseconds() + days * 864e+5);
}
修改为:
if (typeof options.expires === 'number') {
var days = options.expires, t = options.expires = new Date();
t.setMilliseconds(t.getMilliseconds() + days * 864e+5);
} else if (typeof options.expiresHours === 'number') {
var hours = options.expiresHours, t = options.expires = new Date();
t.setMilliseconds(t.getMilliseconds() + hours * 36e+5); // 1小时 = 3600000毫秒
}
现在,可以使用 expiresHours 选项按小时设置过期时间:
$.cookie('tempToken', 'abc123', { expiresHours: 2 }); // 2小时后过期
2. 批量操作 cookie
添加 $.cookie.batchSet 和 $.cookie.batchRemove 方法,支持批量设置和删除 cookie。
在 src/jquery.cookie.js 的末尾,添加以下代码:
// 批量设置 cookie
$.cookie.batchSet = function(cookies, options) {
if (!$.isPlainObject(cookies)) {
throw new Error('cookies must be a plain object');
}
options = $.extend({}, config.defaults, options);
$.each(cookies, function(key, value) {
$.cookie(key, value, options);
});
};
// 批量删除 cookie
$.cookie.batchRemove = function(keys, options) {
if (!$.isArray(keys)) {
throw new Error('keys must be an array');
}
options = $.extend({}, config.defaults, options);
var results = {};
$.each(keys, function(index, key) {
results[key] = $.removeCookie(key, options);
});
return results;
};
使用示例:
// 批量设置 cookie
$.cookie.batchSet({
'username': 'john',
'theme': 'dark',
'layout': 'fluid'
}, { path: '/' });
// 批量删除 cookie
var results = $.cookie.batchRemove(['username', 'theme'], { path: '/' });
console.log(results); // { "username": true, "theme": true }
3. 数据加密存储
为了提高 cookie 中敏感数据的安全性,可以添加数据加密功能。这里使用简单的 Base64 编码作为示例(实际项目中建议使用更安全的加密算法)。
首先,添加编码和解码辅助函数。在 src/jquery.cookie.js 中,stringifyCookieValue 和 parseCookieValue 函数附近添加:
function encrypt(value) {
return btoa(unescape(encodeURIComponent(JSON.stringify(value))));
}
function decrypt(value) {
return JSON.parse(decodeURIComponent(escape(atob(value))));
}
然后,添加 secure 选项,当 secure: true 时自动对数据进行加密:
修改 stringifyCookieValue 函数(第 31-33 行):
function stringifyCookieValue(value) {
if (config.secure) {
return encode(encrypt(value));
}
return encode(config.json ? JSON.stringify(value) : String(value));
}
修改 parseCookieValue 函数(第 35-48 行):
function parseCookieValue(s) {
if (s.indexOf('"') === 0) {
s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
}
try {
s = decodeURIComponent(s.replace(pluses, ' '));
if (config.secure) {
return decrypt(s);
}
return config.json ? JSON.parse(s) : s;
} catch(e) {}
}
最后,在配置中添加 secure 选项:
config.defaults = {
secure: false
};
使用示例:
// 启用加密存储
$.cookie.json = true;
$.cookie.secure = true;
$.cookie('userInfo', { id: 1, name: 'John' }, { path: '/' });
var userInfo = $.cookie('userInfo'); // 自动解密
console.log(userInfo); // { id: 1, name: 'John' }
功能测试与验证
为了确保扩展功能的正确性,需要编写相应的测试用例。打开 test/tests.js,添加以下测试代码:
test("batchSet and batchRemove", function() {
$.cookie.batchSet({
'test1': 'value1',
'test2': 'value2'
}, { path: '/' });
equal($.cookie('test1'), 'value1', 'batchSet test1');
equal($.cookie('test2'), 'value2', 'batchSet test2');
var results = $.cookie.batchRemove(['test1', 'test2'], { path: '/' });
ok(results.test1, 'batchRemove test1');
ok(results.test2, 'batchRemove test2');
equal($.cookie('test1'), undefined, 'test1 removed');
});
test("expiresHours option", function() {
$.cookie('temp', 'value', { expiresHours: 1 });
var date = new Date();
date.setHours(date.getHours() + 1);
var cookie = document.cookie.match(/temp=([^;]+)/);
ok(cookie, 'temp cookie set');
});
test("secure encryption", function() {
$.cookie.json = true;
$.cookie.secure = true;
$.cookie('secret', { key: 'value' }, { path: '/' });
var secret = $.cookie('secret');
deepEqual(secret, { key: 'value' }, 'secure decryption');
$.cookie.secure = false;
$.cookie.json = false;
});
在浏览器中打开 test/index.html,运行测试用例,确保所有新增测试通过。
扩展功能应用场景
用户登录状态管理
利用自定义的过期时间和加密功能,可以实现安全的用户登录状态管理:
// 设置登录状态,2小时后过期
$.cookie.json = true;
$.cookie.secure = true;
$.cookie('loginStatus', { userId: 123, token: 'abcdef' }, {
path: '/',
expiresHours: 2
});
// 检查登录状态
var loginStatus = $.cookie('loginStatus');
if (loginStatus) {
console.log('用户已登录:', loginStatus.userId);
} else {
console.log('用户未登录');
}
网站偏好设置
使用批量操作功能,可以方便地保存和恢复用户的网站偏好设置:
// 保存偏好设置
var preferences = {
theme: 'dark',
layout: 'fluid',
notifications: true
};
$.cookie.batchSet(preferences, { path: '/', expires: 30 });
// 恢复偏好设置
var savedPreferences = {};
var keys = ['theme', 'layout', 'notifications'];
keys.forEach(function(key) {
savedPreferences[key] = $.cookie(key);
});
console.log('用户偏好:', savedPreferences);
总结与展望
通过本文的介绍,你已经掌握了 jQuery-Cookie 插件的扩展方法,实现了自定义过期时间、批量操作和数据加密等实用功能。这些功能可以帮助你更灵活地管理 cookie,满足复杂的业务需求。
虽然 jQuery-Cookie 项目已停止维护并迁移至 js-cookie,但本文介绍的扩展思路和方法同样适用于新的 js-cookie 库。建议关注 js-cookie/js-cookie 项目,了解最新的功能和最佳实践。
未来,你可以进一步探索更多高级功能,如 cookie 过期提醒、跨域 cookie 共享(需服务器配合)、cookie 容量监测等,不断完善和优化 cookie 管理方案。
希望本文对你的学习和开发有所帮助,如有任何问题或建议,欢迎在项目的 Issues 中提出。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考



