Storefront JavaScript API
The AI sales agent and AI Search run as widgets on your store’s pages. This page describes how the two sides talk in the browser: the script you install, what your page can call on window.Yasan, the cart your page can share with the widgets, and the order your confirmation page can describe.
Installation
Paste the installation snippet from Yasan before the closing </body> tag of every page. It is one <script> tag that loads widget.js with your storefront’s token, such as <script src="https://app.yasan.ai/api/chatbot/widget.js?token=…&v=1" async></script>; each storefront has its own token. The widgets only run on the hosts listed under Allowed domains in your storefront’s widget settings, under Domains. Subdomains are covered, so example.com also allows staging.example.com, and ports are ignored, so localhost allows localhost:3000 and localhost:5173 alike. On any other host the widgets show a setup notice instead. See Installing the AI Sales Agent for the platform-specific steps.
Calling the widgets: window.Yasan
| Member | What it does |
|---|---|
Yasan.isReady |
true once the widgets have loaded; see When the widgets are ready. |
Yasan.setConsent({ analytics, marketing }) |
Records the visitor’s cookie choice. Both fields are optional booleans, so you can pass only what changed. Until analytics: true arrives, the widgets send only statistics that do not identify the visitor. See Cookie consent setup. |
Yasan.setLanguage(tag) |
Switches the widgets’ language. Pass the tag as your store spells it, such as cs or de-AT. A tag the widgets have no copy for keeps the default language. |
Yasan.language |
The language the widgets currently show, as a tag. |
Yasan.provide({ getCart, addToCart }) |
Gives the widgets your page’s cart functions, see The cart. Call it only once per page load; calling it again is not allowed. |
Yasan.refreshCart() |
Tells the widgets your cart changed, so they read it again. |
Yasan.reportOrder(order) |
Describes the order your confirmation page shows, see Placed order. |
Yasan.Search.open({ query }) |
Opens AI Search under your search field. With query, it searches for it right away. An open overlay stays as it is. |
Yasan.Search.isEnabled |
true when AI Search is switched on for your store. |
Yasan.Chatbot.open(), close(), toggle() |
Opens, closes or toggles the chat panel. |
Yasan.Chatbot.hide(), show() |
Hides the whole chat widget, launcher included, until show(). Useful under overlays that have no URL of their own, such as a cart popup. Each page load starts visible. |
Yasan.Chatbot.isOpen, isVisible |
Whether the panel is open, and whether the widget is shown. |
Yasan.Chatbot.isEnabled |
true when the AI sales agent is switched on for your store. |
<button type="button" onclick="window.Yasan?.Chatbot.open()">Ask our assistant</button>
<button type="button" onclick="window.Yasan?.Search.open({ query: 'trekking boots' })">Trekking boots</button>
When the widgets are ready
The snippet loads with async, so write window.Yasan?., never a bare Yasan, in code that may run before it. Once widget.js has run, window.Yasan exists, but the widgets themselves load later: when the visitor first interacts with the page or the browser is idle, normally within two seconds of the page loading. Until then:
setConsentsaves the choice at once.setLanguage, theChatbotcontrols andSearch.openare queued. Only the last request of each kind is kept (language, open or closed, hidden or shown, search), and it is applied when the widgets load.provideandreportOrderare queued and applied when the widgets load, in the order you called them.refreshCarthas nothing to do yet: the widgets read your cart when they load.isReadyisfalse.isEnabledalready answers.isVisiblefollows the queuedhide()orshow().isOpenstaysfalseuntil a panel is actually on screen.languageis set once the widgets have loaded.
When the widgets have loaded and the page’s document has loaded too, isReady turns true and right after that the yasan-ready event fires on window, once per page load; its detail.yasan is window.Yasan. The widgets record nothing about the visit before yasan-ready, so a choice your listener passes, such as the visitor’s cookie consent, applies from the first statistic on. The panels are not on screen yet inside the listener: Chatbot and Search calls made there apply as they appear, and Chatbot.isOpen still reads false. Put what your page tells the widgets in one function, and run it once they are ready, whichever loads first:
function setUpYasan() {
window.Yasan.provide({ getCart, addToCart })
window.Yasan.setConsent(currentCookieChoice())
}
if (window.Yasan?.isReady) setUpYasan()
else window.addEventListener('yasan-ready', setUpYasan, { once: true })
The sections below fill in setUpYasan: the cart defines getCart and addToCart, for stores connected through the Connector API, the cookie choice defines currentCookieChoice, and a confirmation page adds the placed order.
If the widgets do not load at all, for example on a host that is not allowed or behind an ad blocker, yasan-ready never fires. Never make anything your shop needs depend on it.
The visitor’s cookie choice
Stores using Cookiebot, CookieYes, OneTrust with its default category IDs, Shoptet’s cookie bar or a Shopify banner that records consent through Shopify’s Customer Privacy API can skip this section: Yasan reads the visitor’s choice from them itself. Otherwise, pass the visitor’s current cookie choice in setUpYasan, and call window.Yasan?.setConsent(…) again in your cookie bar’s change handler. Add the yasan-ready listener before the event fires: the widgets start only once your page’s HTML has been parsed, so code in an inline script or a regular <script> in the page is in time, and the choice is applied before they record anything. Code that can run later, such as a defer or async script, a load handler or a tag from a tag manager, still passes the choice, but the widgets may already have counted the page view with the choice stored on an earlier visit. hasAnalyticsConsent() and hasMarketingConsent() stand for however your page reads the choice:
function currentCookieChoice() {
return { analytics: hasAnalyticsConsent(), marketing: hasMarketingConsent() }
}
// In your cookie bar's change handler:
window.Yasan?.setConsent(currentCookieChoice())
Once your page calls setConsent, Yasan stops reading the cookie bars listed above for the rest of that page load, so your calls win.
The cart
Shoptet, Shopify and WooCommerce stores can skip this section: Yasan reads their carts itself. A store connected through the Connector API has no cart Yasan knows how to reach. Provide two functions and the widgets can use yours:
| You provide | What the widgets do |
|---|---|
getCart |
The AI sales agent sees what is in the cart and can answer questions about it. When the cart empties after checkout, Yasan counts a likely purchase in your statistics. |
addToCart (optional) |
Product cards in the chat and in AI Search show an add-to-cart button, and the AI sales agent adds products when the customer asks, after helping them pick the right variant. |
Without addToCart the cart is read-only: the widgets show no add-to-cart button and the AI sales agent does not offer to add anything.
Provide them in setUpYasan on every page where the widgets run, including the order confirmation page, and call refreshCart() whenever the cart changes, whatever changed it: your own add-to-cart button, a removed line, a completed order. provide takes both in one object, and a later call replaces everything an earlier one provided, so always pass both.
async function getCart() {
const cart = await fetch('/cart.json').then((response) => response.json())
return {
currency: 'CZK',
totalMinor: cart.totalMinor,
items: cart.lines.map((line) => ({
productId: line.productId,
variantId: line.variantId,
title: line.name,
variant: line.variantName,
quantity: line.quantity,
unitPriceMinor: line.unitPriceMinor,
lineTotalMinor: line.totalMinor,
url: line.url,
})),
}
}
async function addToCart({ productId, variantId, quantity }) {
const response = await fetch('/cart/items', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ productId, variantId, quantity }),
})
if (!response.ok) {
const error = new Error('Could not add to cart')
error.code = response.status === 404 ? 'invalid-id' : 'unavailable'
throw error
}
}
// Wherever your page changes the cart:
window.Yasan?.refreshCart()
Your product ids
Cart lines, addToCart and the placed order name a product by two of your own ids, exactly as you sent them to Yasan in GET /products: the product’s id and the variant’s id. A product without real variants has one variant, whose id may be the product id. Yasan matches the pair to the product in its catalog.
getCart
Returns the cart, or a promise of it. Return an empty items list when the cart is empty. All amounts are integers in the currency’s minor unit: 1 298 Kč is 129800, €12.50 is 1250.
| Field | Required | Meaning |
|---|---|---|
currency |
no | ISO 4217 code, such as CZK or EUR. |
totalMinor |
no | What the customer pays for the cart, in minor units. |
items |
yes | Every line of the cart. The widgets count the pieces themselves. |
Each line of items:
| Field | Required | Meaning |
|---|---|---|
title |
yes | Product name, not empty. |
quantity |
yes | Pieces on this line, a whole number of 1 or more. |
productId, variantId |
no | Your product ids. Give both: a line with both is matched to the product in Yasan’s catalog, and a line with neither, or only one, still counts in the cart. |
variant |
no | The variant’s name as the customer sees it, such as size 42. |
unitPriceMinor |
no | Price of one piece, in minor units. |
lineTotalMinor |
no | Price of the whole line, in minor units. |
url |
no | Link to the product page. |
addToCart
Called with { productId, variantId, quantity }: your product ids and the number of pieces to add. Resolve once the cart holds them; throw or reject when it does not. Set code on the error to say why, or leave it out:
error.code |
When |
|---|---|
'invalid-id' |
You do not know this product or variant. |
'unavailable' |
The variant cannot be bought now, for example it is sold out. |
'network' |
Your server could not be reached. |
Any other failure counts as unknown. Either way the widget shows the visitor that the product was not added. A product whose product id and variant id are together longer than about 195 bytes cannot be added from the widgets: they answer that it was not added without calling your function. The widgets wait up to 10 seconds for getCart and addToCart; a call that takes longer counts as failed.
Errors
If getCart throws, rejects or returns something that does not match the tables above, the widgets ignore that cart and write one warning starting with [Yasan] to the browser console. Your page keeps working. A value the widgets cannot use, such as an overly long link, is left out with a warning, and the rest of the cart is kept.
Purchase detection
Yasan counts a likely purchase when a cart that held products is empty on a later page view, which is what usually happens on the order confirmation page. For this to work:
- The installation snippet and your
getCartare on the confirmation page, and it returns the emptied cart there. - The visitor allowed analytics cookies, reported through
Yasan.setConsent.
Testing the cart
- Allow the host you test on, as described under Installation, and add the snippet and your
setUpYasanto the page. - Once the widgets have loaded,
window.Yasan.isReadyanswerstruein the browser console. - Put a product in the cart, open the chat and ask what is in your cart.
- If you provide
addToCart, product cards in the chat show an add-to-cart button. Click one and check that the product lands in your cart. - Keep the console open: a
[Yasan]warning tells you what the widgets could not use.
The preview in the Yasan dashboard does not read your cart. Test on your own pages.
Placed order
On the order confirmation page, report the order that was just placed, in setUpYasan. Its purpose is to let Yasan attribute orders to the searches and conversations that led to them. Yasan checks the reported order but does not record or use it yet; an implementation that follows this page will be picked up without changes on your side.
function setUpYasan() {
window.Yasan.provide({ getCart, addToCart })
window.Yasan.setConsent(currentCookieChoice())
window.Yasan.reportOrder({
orderId: '2026-000123',
currency: 'CZK',
totalMinor: 139700,
items: [
{ productId: '1042', variantId: '1042-42', quantity: 2, unitPriceMinor: 64900 },
],
})
}
| Field | Required | Meaning |
|---|---|---|
orderId |
yes | Your order number. Use the same value every time this order’s confirmation page is shown. |
currency |
yes | ISO 4217 code, such as CZK or EUR. |
totalMinor |
yes | What the customer paid for the whole order, in minor units: the products after discounts, plus shipping and payment fees, VAT included. |
items |
yes | The ordered products. List products only: shipping and fees belong in totalMinor alone. |
Each item:
| Field | Required | Meaning |
|---|---|---|
productId, variantId |
yes | Your product ids, as in the cart. |
quantity |
yes | Pieces ordered, a whole number of 1 or more. |
unitPriceMinor |
yes | Price of one piece as charged in this order, after discounts, VAT included, in minor units. |
Put no customer data in the order: no name, e-mail, phone number, address or customer account id. Yasan does not need it. An order that does not match the tables is ignored with a [Yasan] warning in the browser console.
A checkout that completes without loading a new page reports the order the same way, once it is placed.
Using TypeScript
yasan.d.ts types everything on this page: window.Yasan, the yasan-ready event, the cart, addToCart and its error codes, and the placed order. Save it in your project and add it to the include list of your tsconfig.json, or reference it from the file that uses the widgets:
/// <reference path="./yasan.d.ts" />
Its types can be imported too, such as import type { YasanCart } from './yasan'.