背景

回顾一年前的代码,关于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工具的更多相关文章

  1. js常用工具类.

    一些js的工具类 复制代码 /** * Created by sevennight on 15-1-31. * js常用工具类 */ /** * 方法作用:[格式化时间] * 使用方法 * 示例: * ...

  2. 2015年最佳的15个 Node.js 开发工具

    Node.js 越来月流行,这个基于 Google V8 引擎建立的平台, 用于方便地搭建响应速度快.易于扩展的网络应用.在本文中,我们列出了2015年最佳的15个 Node.js 开发工具.这些工具 ...

  3. 推荐近期15个 Node.js 开发工具

    近来Node.js 越来月流行了,这个基于Google V8 引擎建立的平台, 用于方便地搭建响应速度快.易于扩展的网络应用.在本文中,我们列出了2015年最佳的15个 Node.js 开发工具.这些 ...

  4. atitit js 开发工具 ide的代码结构显示(func list) outline总结

    atitit js 开发工具 ide的代码结构显示(func list) outline总结 eclips环境::4.3.1 #-------需要一个js开发工具,可以显示outline或者代码结构显 ...

  5. 纯JS文本比较工具

    前段时间由于工作需要写了一个纯JS文本比较工具 在这里与大家分享下 算法有待优化,还希望大家多多指教 先上效果图: 奉上源码(把源码保存为html格式的文件就可以直接运行了): <!doctyp ...

  6. 我用的一些Node.js开发工具、开发包、框架等总结

    开发工具 1.WebStorm,毫无疑问非他莫属,跨平台,强大的代码提示,支持Nodejs调试,此外还支持vi编辑模式,这点我很喜欢. 2.做些小型项目用Sublime Text. 3.Browser ...

  7. 推荐15个月 Node.js 开发工具

    Node.js 越来月流行.这个基于 Google V8 引擎建立的平台, 用于方便地搭建响应速度快.易于扩展的网络应用.在本文中.我们列出了2015年最佳的15个 Node.js 开发工具.这些工具 ...

  8. 在线压缩JS的工具

    给大家介绍款在线压缩JS的工具 首先说下该工具的域名:http://javascriptcompressor.com/ 进入后界面如下: 具体要讲下它的功能点:在线压缩 Javascript 源码可以 ...

  9. Node.js开发工具、开发包、框架等总结

    开发工具 1.WebStorm,毫无疑问非他莫属,跨平台,强大的代码提示,支持Nodejs调试,此外还支持vi编辑模式,这点我很喜欢.2.做些小型项目用Sublime Text.3.Browserif ...

  10. Node.js 常用工具

    Node.js 常用工具 util 是一个Node.js 核心模块,提供常用函数的集合,用于弥补核心JavaScript 的功能 过于精简的不足. util.inherits util.inherit ...

随机推荐

  1. PHP之旅8 URL与表单

    表单 表单的出现让用户和后台主机有了直接的交互,网站开始变的‘动态起来’,在HTML的各个标记符中,与PHP关系最为紧密的要属表单标记符了,常见的表单标记符有<form>.<inpu ...

  2. jQuery.cookie的使用指南

    一个轻量级的cookie 插件,可以读取.写入.删除 cookie. 配置 首先包含jQuery的库文件,在后面包含 jquery.cookie.js 的库文件. <script type=&q ...

  3. 如何通过Python暴力破解网站登陆密码

    首先申明,该文章只可以用于交流学习,不可以用于其他用途,否则后果自负. 现在国家对网络安全的管理,越来越严,但是还是有一些不法网站逍遥法外,受限于国内的人力.物力,无法对这些网站进行取缔. 今天演示的 ...

  4. 如何在for循环中使用多线程

    import java.util.concurrent.Executor;import java.util.concurrent.Executors; public class Test {priva ...

  5. UIKit: Apps for Every Size and Shape

    safeArea 即可以正常显示内容的部分.   可以通过 additionalSafeAreaInsets 来调整 safeArea 的大小.  经过调整,范围如下: self.additio ...

  6. ruby:TypeError: 对象不支持此属性或方法(<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolink)

    我整理了一下 目前有三种方法,我是windows 7 64位, 答案中很多人是win8也成功了. 方法1:找到当前项目下 app/javascripts/applications.js  把里面的// ...

  7. Mina的客户端

    (一) package client; import java.net.InetSocketAddress; import java.nio.charset.Charset; import org.a ...

  8. Global Embedding 理解

    1.Attention-based seq2seq e(t,i):求上一时刻的输出和这一时刻编码器的输出的相似度 a(t,i):求这个词在整个文本中占多大的比重,每个时刻都存在着一个值,这个只是求一个 ...

  9. 程序员为什么要写if else,为什么要和别人不一样

    程序员为什么要写if else,为什么要和别人不一样 前言 无聊,睡不着!本文只是随便写写而已!感叹一下程序员的生活! 刚看到一个八级程序员的分级,所以就写了这个随笔,分级如下:        第八级 ...

  10. spring cloud连载第三篇补充之Zuul

    由于Zuul的内容较多所以单独列出一篇来讲.全是干货,如果学到东西的,动动小手给点个推荐^_^  谢谢! 1. Router and Filter: Zuul(路由和过滤:Zuul) 路由是微服务架构 ...