How do I create and read a value from cookie?

前端 未结 19 1728
梦如初夏
梦如初夏 2020-11-21 04:42

How can I create and read a value from a cookie in JavaScript?

19条回答
  •  故里飘歌
    2020-11-21 05:04

    I have written simple cookieUtils, it has three functions for creating the cookie, reading the cookie and deleting the cookie.

    var CookieUtils = {
        createCookie: function (name, value, expireTime) {
            expireTime = !!expireTime ? expireTime : (15 * 60 * 1000); // Default 15 min
            var date = new Date();
            date.setTime(date.getTime() + expireTime);
            var expires = "; expires=" + date.toGMTString();
            document.cookie = name + "=" + value + expires + "; path=/";
        },
        getCookie: function (name) {
            var value = "; " + document.cookie;
            var parts = value.split("; " + name + "=");
            if (parts.length == 2) {
                return parts.pop().split(";").shift();
            }
        },
        deleteCookie: function(name) {
            document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
        }
    };
    

提交回复
热议问题