Skip to content

Instantly share code, notes, and snippets.

@bmodena
Last active September 21, 2022 19:19
Show Gist options
  • Save bmodena/a405144cf1f292ac8039796e1686bd13 to your computer and use it in GitHub Desktop.
Save bmodena/a405144cf1f292ac8039796e1686bd13 to your computer and use it in GitHub Desktop.
Shopify Clear Cart Cookie on logout
/*
@require
Jquery: https://jquery.com/
*/
function delete_cookie(name) {
document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
// logout link
$('a[href^="/account/logout"]').on('click', function(event){
event.preventDefault();
var href = $(this).attr("href"),
target = '';
delete_cookie('cart');
// wait for data to push and then open link
setTimeout(function() { // now wait 150 milliseconds...
window.open(href,(!target?"_self":target)); // ...and open the link as usual
},150);
});
@carlosmirandadiaz
Copy link

Hi,

I try this code, but i don't get results. It's still functional in the last updates of Shopify?

Can you tell me more about how can i implement it?

Thank you

@bmodena
Copy link
Author

bmodena commented Aug 19, 2021

Hi,

I try this code, but i don't get results. It's still functional in the last updates of Shopify?

Can you tell me more about how can i implement it?

Thank you

I would look into - https://shopify.dev/api/ajax/reference/cart#post-cart-clear-js this method above was always a hack prior to this clear cart js ability being added

@QuantumB0x
Copy link

Hi Bmodena,

This is fantastic. Question, can you modify this to have a different trigger? For example, rather than having the user trigger the cart being cleared when logging out, can we use a time frame? Example logic statement: 15 days after the cart was created, the cart clears.

Thanks!

@bmodena
Copy link
Author

bmodena commented Sep 15, 2021

Hi Bmodena,

This is fantastic. Question, can you modify this to have a different trigger? For example, rather than having the user trigger the cart being cleared when logging out, can we use a time frame? Example logic statement: 15 days after the cart was created, the cart clears.

Thanks!

I think by default the Shopify cart expires in 14 days. As far as I know It is not possible to get the expiration date of a cookie through Javascript. So you would have to look into https://shopify.dev/api/ajax/reference/cart GET /cart.js endpoint and it looks like this has a few "created_at": "2019-04-10T20:49:00.148Z", values in the response. If those are tied to cart creation time you could use that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment