Detect cart updates in javascript

Topic summary

A developer is attempting to detect cart updates in JavaScript by adding a script to theme.liquid. Their initial approach using document.addEventListener('cart:updated', ...) is not triggering when clicking “add to cart” on the default store theme.

Proposed Solution:
Another user suggests utilizing PUBSUB EVENTS available in free themes:

  • Check if window.publish, window.subscribe, and PUB_SUB_EVENTS.cartUpdate are defined
  • Subscribe to cart update events using window.subscribe(PUB_SUB_EVENTS.cartUpdate, callback)

Testing Scenarios:
The solution was tested in two scenarios:

  1. Adding items to cart
  2. Increasing/decreasing quantity or removing cart items

Both scenarios successfully logged events to the console, confirming the PUBSUB approach works for detecting cart modifications.

Summarized with AI on November 7. AI used: claude-sonnet-4-5-20250929.

I am trying to add a short script to theme.liquid that detects whenever the cart is updated.

Here’s what I have right now, but it is not working when I click “add to cart” on my default store theme:

document.addEventListener('cart:updated', function(event) {
  console.log('cart updated!');
});

Hi @straversi ,

I realize there are PUBSUB EVENTS on free themes, you can try this

if (window.publish !== undefined && window.subscribe !== undefined && PUB_SUB_EVENTS?.cartUpdate !== undefined) {
    window.subscribe(PUB_SUB_EVENTS.cartUpdate, (e) => console.log(e));
}

Here is the results when I

  1. add to cart

  1. Increase/Decrease quantity or Remove cart items

1 Like