How do I refresh and open the cart drawer with code?
Overview
Another app, a custom button or your own script can add products to the cart without the cart drawer knowing. The cart drawer then still shows the old items. To reload the cart and open the drawer, run this line after the cart changes:
document.dispatchEvent(new CustomEvent("xboost-need-refresh-and-open-cart"));
The cart drawer loads the latest cart, opens, and hides your theme's own cart.
Before you start
- Turn on the app embed and the cart drawer (Cart is active). The cart drawer listens for this event only while it is active. See Getting started with XB: AI Cart Upsell Cart Drawer.
Example
This script adds a product with Shopify's Cart API, then refreshes and opens the cart drawer. Replace 123456789 with the variant ID you want to add:
fetch(window.Shopify.routes.root + "cart/add.js", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ items: [{ id: 123456789, quantity: 1 }] }),
}).then(() => {
document.dispatchEvent(new CustomEvent("xboost-need-refresh-and-open-cart"));
});
Where to add the code
- In your theme code, in the script that adds products to the cart.
- In another app that lets you run custom JavaScript after it adds a product to the cart.
Run the code after the page has loaded. If it runs before the cart drawer is ready, nothing happens.
To test it, open a product page of your store, open your browser's developer console and paste the first line. The cart drawer opens with the current cart.