简单的cookie框架
一个小型框架: 一个完整的cookies读/写器对Unicode充分支持
由于Cookie只是特殊格式的字符串,因此有时很难管理它们。 以下库旨在通过定义一个与一个Storage
对象部分一致的对象(docCookies
)来抽象对document.cookie
的访问。
以下代码也在GitHub上获取。它是基于GNU General Public License v3.0 许可 (许可链接)
库
/*\
|*|
|*| :: cookies.js ::
|*|
|*| A complete cookies reader/writer framework with full unicode support.
|*|
|*| Revision #1 - September 4, 2014
|*|
|*| 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()
|*|
\*/
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;
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) { 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;
}
};
Note: 对于never-expire-cookies 我们使用一个随意的遥远日期
Fri, 31 Dec 9999 23:59:59 GMT
. 处于任何原因,你担心这样一个日期,使用 惯例世界末日Tue, 19 Jan 2038 03:14:07 GMT - 这是自1970年1月1日00:00:00 UTC以来使用 有符号的32位二进制整数表示的最大秒数。(i.e., 01111111111111111111111111111111
which is new Date(0x7fffffff * 1e3)
).cookie的写入
语法
docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
Description
新增/重写一个 cookie.
参数
name
- 新增/重写一个 cookie的 名字 (
字符传
). value
- cookie的值 (
字符串
). end
可选max-age(最大有效时间)单位秒
(e.g.31536e3
表示一年,Infinity
表示永不过期的cookie), 或者以GMTString
格式或者Date
object 的expires
date(过期时间); 如果没有,指定的cookie将在会话结束时到期 (number
– finite orInfinity
–string
,Date
object ornull
).Note: 尽管 officially defined in rfc6265,
max-age
在 Internet Explorer, Edg和一些移动端浏览器上不兼容. 因此,将数字传递给end
参数可能无法按预期工作. 可能的解决方案可能是将相对时间转换为绝对时间。例如,以下代码:docCookies.setItem("mycookie", "Hello world!", 150);
可以使用绝对日期重写,如下例所示:
maxAgeToGMT (nMaxAge) { return nMaxAge === Infinity ? "Fri, 31 Dec 9999 23:59:59 GMT" : (new Date(nMaxAge * 1e3 + Date.now())).toUTCString(); } docCookies.setItem("mycookie", "Hello world!", maxAgeToGMT(150));
在上面的代码中,函数
maxAgeToGMT()
用于从相对时间(即,从“age”)创建GMTString.
path
可选- 可访问此cookie的路径. 例如,“/”,“/ mydir”;如果未指定,则默认为当前文档位置的当前路径(
string
ornull
). The path must be absolute (see RFC 2965). For more information on how to use relative paths in this argument, see this paragraph. domain
可选- 可访问此cookie的域名. 例如,
“example.com”
,“.example.com”
(包括所有子域)或“subdomain.example.com”
; 如果未指定,则默认为当前文档位置的主机端口(string
ornull
). secure
可选- cookie将仅通过https安全协议传输 (
boolean
ornull
).
获取一个cookie
语法
docCookies.getItem(name)
描述
读一个cookie。如果cookie不存在,则返回null值。Parameters
参数
name
- 读取cookie的名字 (
string
).
移除一个cookie
语法
docCookies.removeItem(name[, path[, domain]])
描述
删除一个cookie.
参数
name
- 待移除cookie的名字 (
string
). path
可选- 例如,"
/"
,"/
mydir"
;如果未指定,则默认为当前文档位置的当前路径 (string
ornull
). The path must be absolute (see RFC 2965). For more information on how to use relative paths in this argument, see this paragraph. domain
可选- 例如,
"example.com"
, 或者"subdomain.example.com"
; 如果未指定,则默认为当前文档位置的主机端口(字符串或null),但不包括子域。 (string
ornull
), 但不包括子域名。与早期的规范相反,域名中的前置的点被忽略。如果指定了域,则始终包含子域。Note: 要删除跨子域的cookie,您需要想setItem()样
在removeItem()
中指定domain属性。
检查一个cookie(是否存在)
获取所有cookie列表
Syntax
docCookies.keys()
Description
返回此位置的所有可读cookie的数组。
Example usage:
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!", "Wed, 19 Feb 2127 01:04:55 GMT");
docCookies.setItem("test5", "Hello world!", "Fri, 20 Aug 88354 14:07:15 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;="));