1

Default jQuery method

In my JS (loaded using Require JS) I'm setting a cookie like so:

$.cookie('hideStickyBanner', 1);

This sets a cookie with the expiration date of session which is exactly what I need.

Magento method

But when I try using the mage/cookies method the expiration date defaults to approx 4 days time.

$.mage.cookies.set('hideStickyBannerMagento', 1);

Question

How can I use the $.mage.cookies.set(); function but have the expiration date be the user's session?

I tried this but the expiration still defaulted to 4 days time:

$.mage.cookies.set('hideStickyBannerMagento', 1, {
    expires: 0
});
2

$.mage.cookies.set('name', 'value', {lifetime: -1});

Which seems a little crazy, but here's why...

The source for mage/cookies can be found lib/web/mage/cookies.js. The set method, at least in 2.2.0, sets the expires value with this little snippet:

expires = lifetimeToExpires(options, this.defaults) || options.expires;

I don't know why this was done, but is looks backwards to me. The lifetimeToExpires will add the default lifetime to the current time or to options.expires anytime options.lifetime or defaults.lifetime is greater than 0. That means any value passed in options.expires won't be output to the cookie as is.

Setting options.lifetime to any negative number will cause lifetimeToExpires to return null. Later in the set method when the cookie is created no expiration value will be passed and it will default to session.

  • Ahh I didn't try negative numbers! Agreed it seems weird how they've implemented it, thanks. – Ben Crook Oct 11 '17 at 6:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.