好用的js-cookies工具
背景
回顾一年前的代码,关于cookies这块,增删改查完全可以封装成一个模块。在MDN上看到一款很全的分享,在此做个记录。
cookies模块
/*\
|*|
|*| :: cookies.js ::
|*|
|*| A complete cookies reader/writer framework with full unicode support.
|*|
|*| Revision #5 - August 14th, 2018
|*|
|*| https://developer.mozilla.org/en-US/docs/Web/API/document.cookie
|*| https://developer.mozilla.org/User:fusionchess
|*| https://github.com/madmurphy/cookies.js
|*|
|*| This framework is released under the GNU Public License, version 3 or later.
|*| http://www.gnu.org/licenses/gpl-3.0-standalone.html
|*|
|*| Syntaxes:
|*|
|*| * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
|*| * docCookies.getItem(name)
|*| * docCookies.removeItem(name[, path[, domain]])
|*| * docCookies.hasItem(name)
|*| * docCookies.keys()
|*| * docCookies.clear([path[, domain]])
|*|
\*/ var docCookies = {
getItem: function (sKey) {
if (!sKey) { return null; }
return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
},
setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
var sExpires = "";
if (vEnd) {
switch (vEnd.constructor) {
case Number:
sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
/*
Note: Despite officially defined in RFC 6265, the use of `max-age` is not compatible with any
version of Internet Explorer, Edge and some mobile browsers. Therefore passing a number to
the end parameter might not work as expected. A possible solution might be to convert the the
relative time to an absolute time. For instance, replacing the previous line with:
*/
/*
sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; expires=" + (new Date(vEnd * 1e3 + Date.now())).toUTCString();
*/
break;
case String:
sExpires = "; expires=" + vEnd;
break;
case Date:
sExpires = "; expires=" + vEnd.toUTCString();
break;
}
}
document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
return true;
},
removeItem: function (sKey, sPath, sDomain) {
if (!this.hasItem(sKey)) { return false; }
document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "");
return true;
},
hasItem: function (sKey) {
if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
},
keys: function () {
var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
for (var nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) {
aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]);
}
return aKeys;
},
clear: function (sPath, sDomain) {
var aKeys = this.keys();
for (var nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) {
this.removeItem(aKeys[nIdx], sPath, sDomain);
}
}
}; if (typeof module !== "undefined" && typeof module.exports !== "undefined") {
module.exports = docCookies;
}
cookies示例
docCookies.setItem("test0", "Hello world!");
docCookies.setItem("test1", "Unicode test: \u00E0\u00E8\u00EC\u00F2\u00F9", Infinity);
docCookies.setItem("test2", "Hello world!", new Date(2020, 5, 12));
docCookies.setItem("test3", "Hello world!", new Date(2027, 2, 3), "/blog");
docCookies.setItem("test4", "Hello world!", "Sun, 06 Nov 2022 21:43:15 GMT");
docCookies.setItem("test5", "Hello world!", "Tue, 06 Dec 2022 13:11:07 GMT", "/home");
docCookies.setItem("test6", "Hello world!", 150);
docCookies.setItem("test7", "Hello world!", 245, "/content");
docCookies.setItem("test8", "Hello world!", null, null, "example.com");
docCookies.setItem("test9", "Hello world!", null, null, null, true);
docCookies.setItem("test1;=", "Safe character test;=", Infinity); alert(docCookies.keys().join("\n"));
alert(docCookies.getItem("test1"));
alert(docCookies.getItem("test5"));
docCookies.removeItem("test1");
docCookies.removeItem("test5", "/home");
alert(docCookies.getItem("test1"));
alert(docCookies.getItem("test5"));
alert(docCookies.getItem("unexistingCookie"));
alert(docCookies.getItem());
alert(docCookies.getItem("test1;="));
总结
cookie只是浏览器缓存机制中的一种,由于篇幅有限,会在下一篇文章介绍几种浏览器常用的缓存技术。
cookie.js 作者 github持续更新链接:github传送门
好用的js-cookies工具的更多相关文章
- js常用工具类.
一些js的工具类 复制代码 /** * Created by sevennight on 15-1-31. * js常用工具类 */ /** * 方法作用:[格式化时间] * 使用方法 * 示例: * ...
- 2015年最佳的15个 Node.js 开发工具
Node.js 越来月流行,这个基于 Google V8 引擎建立的平台, 用于方便地搭建响应速度快.易于扩展的网络应用.在本文中,我们列出了2015年最佳的15个 Node.js 开发工具.这些工具 ...
- 推荐近期15个 Node.js 开发工具
近来Node.js 越来月流行了,这个基于Google V8 引擎建立的平台, 用于方便地搭建响应速度快.易于扩展的网络应用.在本文中,我们列出了2015年最佳的15个 Node.js 开发工具.这些 ...
- atitit js 开发工具 ide的代码结构显示(func list) outline总结
atitit js 开发工具 ide的代码结构显示(func list) outline总结 eclips环境::4.3.1 #-------需要一个js开发工具,可以显示outline或者代码结构显 ...
- 纯JS文本比较工具
前段时间由于工作需要写了一个纯JS文本比较工具 在这里与大家分享下 算法有待优化,还希望大家多多指教 先上效果图: 奉上源码(把源码保存为html格式的文件就可以直接运行了): <!doctyp ...
- 我用的一些Node.js开发工具、开发包、框架等总结
开发工具 1.WebStorm,毫无疑问非他莫属,跨平台,强大的代码提示,支持Nodejs调试,此外还支持vi编辑模式,这点我很喜欢. 2.做些小型项目用Sublime Text. 3.Browser ...
- 推荐15个月 Node.js 开发工具
Node.js 越来月流行.这个基于 Google V8 引擎建立的平台, 用于方便地搭建响应速度快.易于扩展的网络应用.在本文中.我们列出了2015年最佳的15个 Node.js 开发工具.这些工具 ...
- 在线压缩JS的工具
给大家介绍款在线压缩JS的工具 首先说下该工具的域名:http://javascriptcompressor.com/ 进入后界面如下: 具体要讲下它的功能点:在线压缩 Javascript 源码可以 ...
- Node.js开发工具、开发包、框架等总结
开发工具 1.WebStorm,毫无疑问非他莫属,跨平台,强大的代码提示,支持Nodejs调试,此外还支持vi编辑模式,这点我很喜欢.2.做些小型项目用Sublime Text.3.Browserif ...
- Node.js 常用工具
Node.js 常用工具 util 是一个Node.js 核心模块,提供常用函数的集合,用于弥补核心JavaScript 的功能 过于精简的不足. util.inherits util.inherit ...
随机推荐
- 【css】——三种方法实现多列等高
html: <section> <div class="item"> Lorem, ipsum dolor sit <div class=" ...
- 【12】JMicro微服务-Zookeeper
如非授权,禁止用于商业用途,转载请注明出处作者:mynewworldyyl 往下看前,建议完成前面1到11小节 1. CuratorFramework支持 JMicro目前基于Zookeeper实现统 ...
- POJ 2291
#include<iostream> #include<stdio.h> using namespace std; int compare(void const *,void ...
- js02--对象、函数、switch、for、异常、表单验证
现在我们接着来继续学习有关js的一些基础. 1.undefined与null undefined:当变量声明但尚未赋值时,它的类型就是undefined null:表示一个不存在的对象,它 ...
- (转)DB2 HADR 监控详解
原文:https://www.ibm.com/developerworks/cn/data/library/techarticles/dm-1010baosf/ HADR 简介 HADR( 高可用性灾 ...
- CSS_Spirte实现原理 分类: HTML+CSS 2015-04-28 22:58 531人阅读 评论(0) 收藏
CSS Spirte就是所谓的把很多的小图标合并成一张大的图片,然后使用CSS的background-position属性,来动态的定位自己需要图标的位置.这样做的目的主要是减少HTTP请求,加快网页 ...
- Pl/SQl 安装和配置Oracle 数据库连接
在进行企业开发时,数据库(oracle)一般在我们本地安装的:另外,oracle数据库比较大,在本地安装,会拖慢电脑的速度.我们可以通过oracle客户端,远程连接数据库.下面介绍自己的安装方式 1. ...
- sql 递归树
with CTE as ( -->Begin 一个定位点成员 select ID, PersonName,ParentID,cast(PersonName as nvarchar(max)) a ...
- Vue中实现token验证
前后端流程分析 前端页面进行登录操作,将用户名和密码发给服务器 服务器进行校验,通过后生成token,包含信息有密匙.uid.过期时间等,然后返回给前端 前端将token保存在本地(建议在localS ...
- UML与ER图
UML 统一建模语言(Unified Modeling Language, UML)是一种描述软件系统结构的图形化语言. 类图 类图用于描述类之间的关系,类图中主要的关系包括: 聚集 带空心菱形的实心 ...