Read a javascript cookie by name

后端 未结 11 1024
盖世英雄少女心
盖世英雄少女心 2020-12-05 06:50

I have set a cookie using

document.cookie = 
    \'MYBIGCOOKIE=\' + value + 
    \'; expires=\' + now.toGMTString() + 
    \'; path=/\';

No

11条回答
  •  旧时难觅i
    2020-12-05 07:26

    Here is an example implementation, which would make this process seamless (Borrowed from AngularJs)

    var CookieReader = (function(){
    var lastCookies = {};
    var lastCookieString = '';
    
    function safeGetCookie() {
        try {
            return document.cookie || '';
        } catch (e) {
            return '';
        }
    }
    
    function safeDecodeURIComponent(str) {
        try {
            return decodeURIComponent(str);
        } catch (e) {
            return str;
        }
    }
    
    function isUndefined(value) {
        return typeof value === 'undefined';
    }
    
    return function () {
        var cookieArray, cookie, i, index, name;
        var currentCookieString = safeGetCookie();
    
        if (currentCookieString !== lastCookieString) {
            lastCookieString = currentCookieString;
            cookieArray = lastCookieString.split('; ');
            lastCookies = {};
    
            for (i = 0; i < cookieArray.length; i++) {
                cookie = cookieArray[i];
                index = cookie.indexOf('=');
                if (index > 0) { //ignore nameless cookies
                    name = safeDecodeURIComponent(cookie.substring(0, index));
    
                    if (isUndefined(lastCookies[name])) {
                        lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
                    }
                }
            }
        }
        return lastCookies;
    };
    })();
    

提交回复
热议问题