Get cookie by name

前端 未结 30 1953
野的像风
野的像风 2020-11-22 03:58

I have a getter to get the value from a cookie.

Now I have 2 cookies by the name shares= and by the name obligations= .

I want to

30条回答
  •  清歌不尽
    2020-11-22 04:32

    Use object.defineProperty

    With this, you can easily access cookies

    Object.defineProperty(window, "Cookies", {
        get: function() {
            return document.cookie.split(';').reduce(function(cookies, cookie) {
                cookies[cookie.split("=")[0]] = unescape(cookie.split("=")[1]);
                return cookies
            }, {});
        }
    });
    

    From now on you can just do:

    alert( Cookies.obligations );
    

    This will automatically update too, so if you change a cookie, the Cookies will change too.

提交回复
热议问题