Magento 1 – Mage.Cookies.clear() Not Working

cookiejavascriptmagento-1

The JavaScript function Mage.Cookies.clear does not clear any cookie. It does not matter if the cookie was set with Mage.Cookies.set or from PHP.

Cookie configuration:

  • Cookie Lifetime: 3600
  • Cookie Path: /
  • Cookie Domain: www.example.com
  • Use HTTP Only: No
  • Cookie Restriction Mode: No

I noticed it on Magento EE 1.14.2 but tagging the question as since it seems to be a general problem in cookies.js which has not changed in ages.

How can I solve this?

Best Answer

Having a look at the function:

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

it looks like path and domain are missing. Also the date string is not in the correct format (see: https://stackoverflow.com/questions/11136372/which-date-formats-can-i-use-when-specifying-the-expiry-date-when-setting-a-cook)

The function is not used anywhere in core Magento, probably that's why nobody noticed it was broken for 8 years.

I was able to fix this by redefining the function to use Mage.Cookies.set which takes care of all required parameters:

Mage.Cookies.clear = function(name) {
  if(Mage.Cookies.get(name)){
    Mage.Cookies.set(name, '', new Date(0));
  }
};

While we're at it, Mage.Cookies.set uses Date.toGMTString() which is deprecated and while it's still widely supported, it will not work in future browser versions. Changing it to toUTCString makes the cookie functions future proof.

Related Topic