How do I create and read a value from cookie?

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

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

相关标签:
19条回答
  • 2020-11-21 04:55

    I use this object. Values are encoded, so it's necessary to consider it when reading or writing from server side.

    cookie = (function() {
    
    /**
     * Sets a cookie value. seconds parameter is optional
     */
    var set = function(name, value, seconds) {
        var expires = seconds ? '; expires=' + new Date(new Date().getTime() + seconds * 1000).toGMTString() : '';
        document.cookie = name + '=' + encodeURIComponent(value) + expires + '; path=/';
    };
    
    var map = function() {
        var map = {};
        var kvs = document.cookie.split('; ');
        for (var i = 0; i < kvs.length; i++) {
            var kv = kvs[i].split('=');
            map[kv[0]] = decodeURIComponent(kv[1]);
        }
        return map;
    };
    
    var get = function(name) {
        return map()[name];
    };
    
    var remove = function(name) {
        set(name, '', -1);
    };
    
    return {
        set: set,
        get: get,
        remove: remove,
        map: map
    };
    
    })();
    
    0 讨论(0)
  • 2020-11-21 05:01

    Mozilla provides a simple framework for reading and writing cookies with full unicode support along with examples of how to use it.

    Once included on the page, you can set a cookie:

    docCookies.setItem(name, value);
    

    read a cookie:

    docCookies.getItem(name);
    

    or delete a cookie:

    docCookies.removeItem(name);
    

    For example:

    // sets a cookie called 'myCookie' with value 'Chocolate Chip'
    docCookies.setItem('myCookie', 'Chocolate Chip');
    
    // reads the value of a cookie called 'myCookie' and assigns to variable
    var myCookie = docCookies.getItem('myCookie');
    
    // removes the cookie called 'myCookie'
    docCookies.removeItem('myCookie');
    

    See more examples and details on Mozilla's document.cookie page.

    A version of this simple js file is on github.

    0 讨论(0)
  • 2020-11-21 05:01

    Simple way to read cookies in ES6.

    function getCookies() {
        var cookies = {};
        for (let cookie of document.cookie.split('; ')) {
            let [name, value] = cookie.split("=");
            cookies[name] = decodeURIComponent(value);
        }
        console.dir(cookies);
    }
    
    0 讨论(0)
  • 2020-11-21 05:01

    You can use my cookie ES module for get/set/remove cookie.

    Usage:

    In your head tag, include the following code:

    <script src="https://raw.githack.com/anhr/cookieNodeJS/master/build/cookie.js"></script>
    

    or

    <script src="https://raw.githack.com/anhr/cookieNodeJS/master/build/cookie.min.js"></script>
    

    Now you can use window.cookie for store user information in web pages.

    cookie.isEnabled()

    Is the cookie enabled in your web browser?

    returns {boolean} true if cookie enabled.
    

    Example

    if ( cookie.isEnabled() )
        console.log('cookie is enabled on your browser');
    else
        console.error('cookie is disabled on your browser');
    

    cookie.set( name, value )

    Set a cookie.

    name: cookie name.
    value: cookie value.
    

    Example

    cookie.set('age', 25);
    

    cookie.get( name[, defaultValue] );

    get a cookie.

    name: cookie name.
    defaultValue: cookie default value. Default is undefined.
    returns cookie value or defaultValue if cookie was not found
    
    Example
    var age = cookie.get('age', 25);
    

    cookie.remove( name );

    Remove cookie.

    name: cookie name.
    
    Example
    cookie.remove( 'age' );
    

    Example of usage

    0 讨论(0)
  • 2020-11-21 05:02
    function setCookie(cname,cvalue,exdays) {
        var d = new Date();
        d.setTime(d.getTime() + (exdays*24*60*60*1000));
        var expires = "expires=" + d.toGMTString();
        document.cookie = cname+"="+cvalue+"; "+expires;
    }
    
    function getCookie(cname) {
        var name = cname + "=";
        var ca = document.cookie.split(';');
        for(var i=0; i<ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1);
            if (c.indexOf(name) == 0) {
                return c.substring(name.length, c.length);
            }
        }
        return "";
    }
    
    function checkCookie() {
        var user=getCookie("username");
        if (user != "") {
            alert("Welcome again " + user);
        } else {
           user = prompt("Please enter your name:","");
           if (user != "" && user != null) {
               setCookie("username", user, 30);
           }
        }
    }
    
    0 讨论(0)
  • 2020-11-21 05:04

    An improved version of the readCookie:

    function readCookie( name )
    {
        var cookieParts = document.cookie.split( ';' )
        ,   i           = 0
        ,   part
        ,   part_data
        ,   value
        ;
    
        while( part = cookieParts[ i++ ] )
        {
            part_data = part.split( '=' );
    
            if ( part_data.shift().replace(/\s/, '' ) === name )
            {
                value = part_data.shift();
                break;
            }
    
        }
        return value;
    }
    

    This should break as soon as you have found your cookie value and return its value. In my opinion very elegant with the double split.

    The replace on the if-condition is a white space trim, to make sure it matches correctly

    0 讨论(0)
提交回复
热议问题