版权声明:
尊重知识产权,严厉打击非法采集。
使用JavaScript读写浏览器的Cookies,网络上有许多代码都写得太复杂累赘,我写个简洁的。
代码如下:
Cookie =
{
get: function (k) { return ((new RegExp(["(?:; )?", k, "=([^;]*);?"].join(""))).test(document.cookie) && RegExp["$1"]) || ""; },
set: function (k, v, e, d) { document.cookie = [k, "=", v, e && e["toGMTString"] ? ';expires=' + e.toGMTString() : "", ";path=/;domain=", d || ""].join(""); },
del:function(k){ document.cookie = [k, "=", "", ';expires=' + new Date(new Date().getTime()-99).toGMTString(), ";path=/;domain=", ""].join(""); },
};
// 简单写入
Cookie.set("UserID", "Hello hooyes");
// 设置有效期
Cookie.set("UserID", "Hello hooyes",new Date("2020-04-08 23:59:59"));
var val = Cookie.get("UserID");
Cookie.del("UserID");
$ welcome to hooyes.net
[INFO] ------------------------------o-
[INFO] Author : HOOYES
[INFO] Site : https://hooyes.net
[INFO] Page : https://hooyes.net/p/javascript-cookies
[INFO] Last build : 2023-07-31 09:16:20 +0000
[INFO] -0------------------------------