Extracting cookies using Javascript

Cookies in the current page can be extract using Javascript using ‘document.cookies’ which returns a ‘;’ separated String of all the current cookie values.

You can parse the values with some script like this:

function getCookie(name) {
    var result = '';
    var cookies = document.cookie.split(';');
    for ( var i = 0; i < cookies.length; i++) {
        //alert(cookies[i]);
        var cookie = cookies[i].split('=');
        if (cookie[0].replace(/^s+|s+$/g, '') == name)
            result = cookie[1];
    }
    return result;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.