Get cart total value in Shopify Custom Pixel product_added_to_cart Event

Hi! Im currently working on implementing some tracking pixel with the new Web Pixels API.

When the product_added_to_cart (as well as removed) event is called I need to get the new total cart value.

How can I do this?

Thank you!

Hi,

It can be done by setting up custom event listeners and making requests to the /cart.js endpoint whenever a product is added or removed from the cart.

Use the total_price property from the fetched cart data to get the total value and incorporate it into your tracking pixels as needed.

Define the Event Listener and Fetch Cart Data code example

// Define your pixel script
(() => {
  // Listen for `product_added_to_cart` event
  Shopify.CustomerEvents.subscribe('product_added_to_cart', async (event) => {
    console.log("Product added to cart:", event);
    // Fetch cart details
    const cart = await getCartDetails();
    console.log("Updated Cart Total:", cart.total_price / 100); // Cart total in dollars
  });

  // Listen for `product_removed_from_cart` event
  Shopify.CustomerEvents.subscribe('product_removed_from_cart', async (event) => {
    console.log("Product removed from cart:", event);
    // Fetch cart details
    const cart = await getCartDetails();
    console.log("Updated Cart Total:", cart.total_price / 100); // Cart total in dollars
  });

  // Function to fetch cart details
  async function getCartDetails() {
    try {
      const response = await fetch('/cart.js'); // Shopify's default cart endpoint
      const cart = await response.json();
      return cart;
    } catch (error) {
      console.error("Error fetching cart details:", error);
    }
  }
})();

Hi, im doing the same, except i use

“analytics.subscribe(‘product_added_to_cart’, async (event) =>…” cause i use the remix shopify app template , which i think should be fine? and my app is running in development.

i keep getting the error saying “requests are not allowed from the same origin”, do you happen to know how to fix it?