Shopify Users
Step 1: Open the Code Editor
Go to: Shopify Admin > Online Store > Themes.
Click Edit Code to open the theme’s code editor.
Step 2: Locate the
theme.liquid
FileIn the theme editor sidebar, under Layout, click on theme.liquid.
Step 3: Insert the Code
Scroll to the end of the
<head>
section.Paste the following code just above the
</head>
tag:
const subscribeToTolstoyAddToCartClick = () => { const myCallback = (payload) => { // Your logic here }; const options = {}; window.tolstoyWidget.subscribe("tolstoy_add_to_cart", myCallback, options); }; if (window.tolstoyWidget) { subscribeToTolstoyAddToCartClick(); } else { window.addEventListener("tolstoyWidgetReady", () => { subscribeToTolstoyAddToCartClick(); // Additional logic... }); }
Step 4: Customize the Code
Find the line in the pasted code that says
// Your logic here
.Replace this comment with your own "Add To" function to define the custom functionality.
Step 5: Save the File
Once the code is added and customized, click Save to apply the changes.
Here’s the document you can use as a reference.
Add to cart trigger for Headless
Steps to integrate add to cart function to headless site
Go to your theme.liquid and add the script below.
Alternatively, create a JS file and call that file inside your theme, and paste this code inside.
const subscribeToTolstoyAddToCartClick = () => { const myCallback = (payload) => { const { variantId, productId } = payload; // Your logic here - Add to cart with the productId/variantId if (success) { window.tolstoyWidget.postMessage({ ...payload, eventName: "tolstoy_add_to_cart_success", }); } else { window.tolstoyWidget.postMessage({ ...payload, eventName: "tolstoy_add_to_cart_error", description: "itemSoldOut", // Optional description }); } }; window.tolstoyWidget.subscribe("tolstoy_add_to_cart", myCallback); }; if (window.tolstoyWidget) { subscribeToTolstoyAddToCartClick(); } else { window.addEventListener("tolstoyWidgetReady", () => { subscribeToTolstoyAddToCartClick(); }); }
2. Add your logic in the commented line // Your logic here - Add to cart with the productId/variantId
and return success true/false.
For products to appear on site's cart without refreshing the page
You need to place your refresh cart function inside the myCallback
here.
const subscribeToTolstoyAddToCartClick = () => { const myCallback = (payload) => { // Your logic here }; const options = {}; window.tolstoyWidget.subscribe("tolstoy_add_to_cart", myCallback, options); }; if (window.tolstoyWidget) { subscribeToTolstoyAddToCartClick(); } else { window.addEventListener("tolstoyWidgetReady", () => { subscribeToTolstoyAddToCartClick(); // Additional logic... }); }
Need help?
You can reach out to our friendly support team in two ways:
Via email at support@gotolstoy.com.
Using our live chat option, which can be found by clicking on the chat icon on any Tolstoy page in the lower right corner.