How do I create and read a value from cookie?

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

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

19条回答
  •  予麋鹿
    予麋鹿 (楼主)
    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.

提交回复
热议问题