Cookie Operation in JavaScript

Nowadays people tend to use localStorage instead of cookie for lots of obvious benefits, but in some cases cookie is still useful. In this post, I would like to share a few code snippet, which is such a case where cookie can meet our needs easily. Sometimes, you want to do some stuff, say testing a Google Chrome extension, but only when starting browser at the very first time. You can achieve this by creating, reading, and trashing cookie. Then here you go:

/* By setting expires to 0, the cookie is trashed when the user closes the browser.*/
function createCookie(name, value, expires) {
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var cname = name + "=";
    var cookies = document.cookie.split(';');
    for (var i = 0, j = cookies.length; i < j; i++) {
        var c = cookies[i];
        c = c.substr(c.indexOf(' ') + 1);
        if (c.indexOf(cname) == 0)
            return c.substr(cname.length);
    }
    return null;
}

function eventHandler() {
    var flag = readCookie("geniuscarrier");
    if (!flag) {
        // do the stuff
        createCookie("geniuscarrier", "1", 0);
    }
}

Yang Zhao

Read more posts by this author.


Comment