Skip to main content
Version: 2.0.0

The window.yui object

yStore exposes a global window.yui object on every storefront page. It provides context about the current session and a set of helper utilities for use in Alpine.js components, custom scripts, and theme overrides.

Page context properties

These properties are set by the server on each page load and reflect the current visitor's session state.

PropertyTypeDescription
cartIdstringThe current cart / quote ID
siteIdnumberCraft CMS site ID for the current request
currencystringActive currency code (e.g. "EUR", "USD")
isLoggedInbooleanWhether the visitor is a logged-in customer
customerobject|nullCustomer object when logged in, otherwise null

Example usage in an Alpine component:

if (window.yui.isLoggedIn) {
console.log('Welcome back,', window.yui.customer.firstName);
}

yui.getCookie(name)

Returns the value of the named cookie, or undefined if it does not exist.

const consent = yui.getCookie('cookie-consent');

yui.setCookie(name, value, days, skipSetDomain)

Sets a cookie. name and value are required. days and skipSetDomain are optional.

skipSetDomain prevents the domain being set on the cookie. This is needed in some cases because Craft CMS does not always set the domain on its own cookies — setting it inconsistently would result in duplicate cookies for the same key.

info

By default, cookies are only saved when the visitor has given their consent.


yui.setSessionCookie(name, value, skipSetDomain)

Identical to yui.setCookie but the cookie has no expiry, so it is deleted when the browser session ends (i.e. when all tabs for the site are closed).


yui.getBrowserStorage()

Returns localStorage if available, falling back to sessionStorage. Returns false if neither is available (e.g. iOS Safari in private mode), and logs a warning to the console.

const browserStorage = yui.getBrowserStorage();
if (browserStorage) {
// Read
const value = browserStorage.getItem('my-key');

// Write
browserStorage.setItem('my-key', 'my-value');

// Delete
browserStorage.removeItem('my-key');
}

yui.getFormToken()

Returns the current CSRF token value. It is read from the CSRF cookie, or generated fresh if the cookie does not exist. Use this when constructing form submissions or fetch requests that require a CSRF token.

const token = yui.getFormToken();

yui.postForm(postParams)

Creates a hidden <form>, populates it with the provided data object as hidden fields, and submits it. Automatically includes uenc and csrf fields.

postParams shape:

{
action: 'https://example.test/actions/yui/cart/add',
data: {
sku: 'PROD-001',
qty: 1
},
skipUenc: false, // optional — omit the uenc field
}

Example — post via an Alpine.js click handler:

<a href="#" @click.prevent="yui.postForm({
action: '/actions/yui/quote/move',
data: { id: '{{ quoteId }}' }
})">Move to Quote</a>

yui.getUenc()

Returns a properly encoded version of window.location.href suitable for use as a uenc parameter. This is used by some yStore actions to redirect the visitor back to the originating page after form submission.

const body = 'csrf=' + yui.getFormToken() + '&uenc=' + yui.getUenc();

yui.formatPrice(value, showSign, options)

Formats a numeric value using the active currency and locale. Returns a formatted string.

  • showSign (optional) — if true, always renders + or -. By default only - is shown for negative values.
  • options (optional, since 0.16.2) — passed directly to Intl.NumberFormat.
yui.formatPrice(9.99)           // "€9.99"
yui.formatPrice(9.99, true) // "+€9.99"
yui.formatPrice(-5, true) // "-€5.00"

Override example — remove fraction digits site-wide from a custom theme:

(() => {
const origFormatPrice = yui.formatPrice;
yui.formatPrice = function (value, showSign, options = {}) {
options.maximumFractionDigits = 0;
return origFormatPrice.call(null, value, showSign, options);
};
})();

yui.str(string, ...args)

Replaces positional placeholders (%1, %2, …) in a string with the provided arguments. The first argument maps to %1.

yui.str('%2 %1 %3', 'a', 'b', 'c') // => "b a c"
yui.str('Welcome %1', customer.firstName)

Use %%1 to produce a literal %1 in the output.

This mirrors Craft's PHP Craft::t() positional syntax, so translation strings can be shared between PHP and JavaScript:

// PHP
Craft::t('yui', 'Welcome %1', [$customer->getFirstname()])
// JavaScript
yui.str('Welcome %1', customer.firstName)

yui.strf(string, ...args)

Identical to yui.str except the first argument maps to %0 instead of %1.

yui.strf('%1 %0 %2', 'a', 'b', 'c') // => "b a c"
yui.str vs yui.strf

Prefer yui.str when your strings might also be used with PHP's Craft::t(), which uses %1 for the first argument. Use yui.strf when working with zero-indexed placeholders.


yui.trapFocus(rootElement)

Constrains keyboard tab navigation to focusable elements within rootElement. The first focusable element is focused automatically. Useful for modals and drawers.

yui.trapFocus(document.querySelector('#cart-drawer'));

Release with yui.releaseFocus(rootElement), or by hiding / removing the element.


yui.releaseFocus(rootElement)

Removes the focus trap set by yui.trapFocus.

yui.releaseFocus(document.querySelector('#cart-drawer'));

yui.replaceDomElement(targetSelector, content)

Replaces the DOM element matching targetSelector with the equivalent element extracted from the HTML string content. Script tags inside the new content are moved to the document head so they execute correctly.

Useful for swapping out a page section after an Ajax response:

window.fetch(url, { method: 'POST', body: payload })
.then(res => res.text())
.then(body => yui.replaceDomElement('#product-form', body))
.catch(err => {
console.error(err);
window.location.reload();
});

yui.activateScripts(node)

Extracts all <script> child elements from a given DOM Element and appends them to the document head so the browser parses and executes them. Use this when injecting raw HTML snippets that contain scripts.

const wrapper = document.createElement('div');
wrapper.innerHTML = htmlSnippet;
yui.activateScripts(wrapper);
document.querySelector('#target').replaceWith(wrapper);

yui.alpineInitialized(callback)

Executes callback after Alpine.js is fully loaded and initialized, regardless of Alpine version (v2 or v3). More reliable than the document load event on cached pages in mobile Safari.

yui.alpineInitialized(() => {
console.log('Alpine is ready');
});

yui.postLog(message, output, type)

Sends a log entry via fetch to the server-side logger. Messages appear in the CraftCMS admin panel under the plugin's Logs section. Useful for surfacing client-side errors server-side.

try {
// code
} catch (error) {
yui.postLog(error.message);
}