Handling cookies in Magento with JavaScript

In order to handle cookies in Magento refer to /js/mage/cookies.js. The functions for getting, settings and clearing cookies are:

  • Mage.Cookies.set
  • Mage.Cookies.get
  • Mage.Cookies.clear

Below you find the corresponding JavaScript functions from cookies.js:

Mage.Cookies.set = function(name, value) {
     var argv = arguments;
     var argc = arguments.length;
     var expires = (argc > 2) ? argv[2] : Mage.Cookies.expires;
     var path = (argc > 3) ? argv[3] : Mage.Cookies.path;
     var domain = (argc > 4) ? argv[4] : Mage.Cookies.domain;
     var secure = (argc > 5) ? argv[5] : Mage.Cookies.secure;
     document.cookie = name + "=" + escape (value) +
       ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
       ((path == null) ? "" : ("; path=" + path)) +
       ((domain == null) ? "" : ("; domain=" + domain)) +
       ((secure == true) ? "; secure" : "");
};

Mage.Cookies.get = function(name){
    var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    var j = 0;
    while(i < clen){
        j = i + alen;
        if (document.cookie.substring(i, j) == arg)
            return Mage.Cookies.getCookieVal(j);
        i = document.cookie.indexOf(" ", i) + 1;
        if(i == 0)
            break;
    }
    return null;
};

Mage.Cookies.clear = function(name) {
  if(Mage.Cookies.get(name)){
    document.cookie = name + "=" +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
};

Generic cookie clear function

In case you are searching for a simple, generic function to clear (Magento) session cookies you might want to use the following snippet ($vhost is the current VHost determined by PHP’s globals, e.g. www.yoursite.com):

function clearCookie(name, domain, path) {
  var domain = domain || document.domain;
  var path = path || "/";
  console.debug(name + "=; expires=" + +new Date + "; domain=" + domain + "; path=" + path);
  document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT;domain=" + domain + ";path=" + path;
}

try {
  console.debug('Removing session cookie...');
  clearCookie('frontend', '<!--?php echo $vhost; ?-->', '/');
  console.debug('Removed cookie');
} catch (Error) {
  console.error('Failed to remove cookie');
}

You may also like...

Leave a Reply

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