Javascript Cookie Functions

Updated . Posted . Visible to the public.

This doesn't really go here, but hey ho. Magento's functions in js/Mage/cookies.js are not very good.

/**
 * Get a cookie value
 *
 * @param String name The cookie name
 *
 * @return String The cookie value
 */
getCookie: function(name)
{
    var val = '';
    var cookies = document.cookie.split('; ');
    for (i = 0; i < cookies.length; i++) {
        nameVal  = cookies[i].split('=');
        if (nameVal[0] == name) {
            val = unescape(nameVal[1]);
        }
    }
    return val;
}

/**
 * Set a cookie, or unset it by passing -1 as the expires param
 *
 * It is very important to pass *exactly* what was used to set the cookie in
 * the first place - this means same name, path, domain and secure. If the
 * cookie is host-only (had no domain passed in when set) then pass null as
 * the domain parameter, however if a domain was used when the cookie was
 * set then it will need a peiod prefix (.www.whatever.com) as the domain
 *
 * @param String name    The cookie name
 * @param String value   What to set to, use '' to unset
 * @param Int    expires Expiry in seconds, -1 to unset
 * @param String path    The path, when unsetting must be exactly as when set
 * @param String domain  The domain, when unsetting must be exactly as when set
 * @param Bool   secure  Secure or not, when unsetting must be exactly as when set
 *
 * @return void
 */
setCookie: function(name, value, expires, path, domain, secure)
{
    var cookieStr = name + "=" + escape(value) + "; ";
    if (expires) {
        var expiresDate = new Date(new Date().getTime() + expires * 24 * 60 * 60 * 1000);
        cookieStr += "expires=" + expiresDate.toGMTString() + "; ";
    }
    if (path) {
        cookieStr += "path=" + path + "; ";
    }
    if (domain) {
        cookieStr += "domain=" + domain + "; ";
    }
    if (secure) {
        cookieStr += "secure; ";
    }
    document.cookie = cookieStr;
}

Mike Whitby
Last edit
Posted by Mike Whitby to Magento (2012-06-28 12:08)