Reader small image

You're reading from  React Components

Product typeBook
Published inApr 2016
Publisher
ISBN-139781785889288
Edition1st Edition
Tools
Right arrow
Author (1)
Christopher Pitt
Christopher Pitt
author image
Christopher Pitt

Christopher Pitt is a principal developer for SilverStripe in Wellington, New Zealand. He usually works on open source software, though sometimes you'll find him building compilers and robots.
Read more about Christopher Pitt

Right arrow

Storing cookies


You must have heard of cookies before. They're a browser-based storage mechanism as old as the Internet, and they are often comically described in movies. Here's how we use them:

document.cookie = "pages=all_the_pages";
document.cookie = "current=current_page_id";

The document.cookie parameter works as a temporary string store. You can keep adding new strings, where the key and value are separated by =, and they will be stored beyond a page reload, that is, until you reach the limit of how many cookies your browser will store per domain. If you set document.cookie multiple times, multiple cookies will be set.

You can read the cookies back again, with a function like this:

var cookies = {};

function readCookie(name) {
    var chunks = document.cookie.split("; ");

    for (var i = chunks.length - 1; i >= 0; i--) {
        var parts = chunks[i].split("=");
        cookies[parts[0]] = parts[1];
    }

    return cookies[name];
}

export default readCookie;

The whole cookie string...

lock icon
The rest of the page is locked
Previous PageNext Page
You have been reading a chapter from
React Components
Published in: Apr 2016Publisher: ISBN-13: 9781785889288

Author (1)

author image
Christopher Pitt

Christopher Pitt is a principal developer for SilverStripe in Wellington, New Zealand. He usually works on open source software, though sometimes you'll find him building compilers and robots.
Read more about Christopher Pitt