hooyes

原创一段简洁的JS读写Cookie的代码

|2013-05-10

请尊重原创,本文原文地址:https://hooyes.net/p/javascript-cookies

使用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

// 简单写入
Cookie.set("UserID", "Hello hooyes");

// 设置有效期
Cookie.set("UserID", "Hello hooyes",new Date("2020-04-08 23:59:59"));

读取Cookie

var val = Cookie.get("UserID");

删除Cookie

Cookie.del("UserID");
https://hooyes.net/p/javascript-cookies
https://hooyes.net/p/javascript-cookies
$ 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------------------------------
原文地址:https://hooyes.net/p/javascript-cookies
原文地址:https://hooyes.net/p/javascript-cookies
Content
...
TOP