Skip to main content

JavaScript API

At runtime the frontend exposes everything through the global window.FPD object. The same object also serves as the input configuration (see Configuration) — the bundle merges its runtime state into whatever your theme defined before load.

Runtime objects​

PropertyWhat it is
FPD.instanceThe live FancyProductDesigner instance — the main scripting surface (see below). Exists after the designer was created on a product page.
FPD.productPageThe product page orchestrator (see below).
FPD.CartPageCart page handler (cart page only).
FPD.generalPageAJAX-cart handler (all pages).
FPD.optionsManagerAccess to all resolved options and feature flags.
FPD.taThe resolved theme-abstraction selector tree (product, cart, cartJS, modal).
FPD.shopOptionsThe merged shop options.
FPD.utils{ deepMerge, formatPrice } helpers.
FPD.formatMoneyShopify money formatter.
FPD.funcCallable helpers (see below).

FPD.func.*​

FunctionPurpose
FPD.func.fpdDebug()Highlights and logs all theme-abstraction selectors on the page — the fastest way to see whether FPD found your form, button, and container.
FPD.func.updateCartImages()Re-runs cart page thumbnail replacement.
FPD.func.updateCartJSImages()Re-runs AJAX-cart/drawer thumbnail replacement.

FPD.instance — the designer​

The designer instance follows the Fancy Product Designer API. The most useful members for integrators:

const fpd = FPD.instance;

fpd.calculatePrice(); // current total customization price
fpd.getElements(); // all elements of the current view
fpd.getCustomElements('all') // elements the customer added
fpd.currentViewInstance // active view (fabricCanvas etc.)
fpd.viewInstances // all views
fpd.loadProduct(productJson) // load an FPD product programmatically

fpd.addEventListener('ready', ...);
fpd.addEventListener('productCreate', ...);
caution

FPD.instance is replaced when the designer is re-initialized (e.g. after certain variant changes). Don't keep long-lived references; re-read FPD.instance or re-attach listeners on productCreate.

FPD.productPage​

MemberPurpose
getPluginOption(path)Read any per-product plugin option by path, e.g. getPluginOption('langJSON').
getShopifyProduct()The Shopify product JSON (from #ProductJson-FPD).
getCurrentShopifyVariant()The currently selected variant (from the URL).
getAtcBehavior()'add' or 'update' (update = editing an existing cart line).
updateTa(path, value)Change a theme-abstraction selector at runtime.
reinitializeDesigner()Full designer rebuild — use after your theme morphs the surrounding DOM.
debugTa()Same as FPD.func.fpdDebug().
existingLicThe loaded saved design when the page was opened via an edit link, otherwise unset.

Callbacks (FPD.callbacks)​

Callbacks are functions your theme provides before the bundle loads; the frontend invokes them at defined points. This is the supported way to customize flow behavior.

window.FPD = window.FPD || {};
window.FPD.callbacks = {
beforeAddToCart(form) {
// validate; throw to abort the add-to-cart
},
addToCart(addedProduct) {
// after a successful add
},
};

Add-to-cart flow​

CallbackSignaturePurpose
beforeAddToCart(form)Runs before the add. Throwing aborts the add-to-cart — use for custom validation.
bulkPositions(form) => [{id, quantity}] | nullFor themes that collect quantities themselves (e.g. a size grid). Return one { id: variantId, quantity } per variant and the add-to-cart button orders one cart line per position (same design, own _fpd-hash each) instead of one line with the selected variant. Return null for the regular add; an empty array or throwing aborts the add-to-cart. Form properties are not carried over. Not called while editing a cart item. The configured after-add-to-cart strategy applies, except submit_form, which goes to the cart.
addToCart(addedProduct)After a successful add.
addToCartDone({ success, error })Once per add-to-cart click, whatever the outcome — for a shop's own "added to cart" message. success is whether the product went into the cart. error is set when the add failed with an error; the shopper has already been shown a message for it (the cart's own reason when Shopify refused the add, e.g. sold out). success: false without error: a failure FPD reported itself (elements outside the printable area, a bulk error) or a beforeAddToCart / bulkPositions abort. Also dispatched on document as the event fpd:addToCartDone with the same detail.
addProductToForm(form)Replaces the default form.submit() under the submit_form strategy; also called after bulk-order adds with (form, data).
triggerCartDrawer(response)Open your own cart drawer under the trigger_cart_drawer strategy.
cartSections() => string[]Section IDs to request from /cart/add.js (Section Rendering API).

Line item properties​

CallbackSignaturePurpose
cartTextPropertiesPost(properties, lineItemCache, shopifyProduct) => propertiesRewrite the line item properties before they are written. Keep all _fpd* keys!
afterSaveCustomization(properties) => propertiesSame, for the save-button flow.

Custom products (LIC)​

CallbackSignaturePurpose
onLicCreated(lic, resolve)Intercept after the design was stored; must call resolve() to continue.
newProductName(shopifyProduct, variantId) => stringName for a generated custom product.
extraTags(shopifyProduct, variantId) => tagsExtra tags for a generated custom product.

Page lifecycle & UI​

CallbackSignaturePurpose
productPageDone()Product page init finished (designer may still be loading).
afterProductLoaded(fpdProductJSON)The FPD product configuration was loaded.
elementModify(isCustomized)An element changed.
mainImageReplaceCallback(imageEl, previewDataUrl)Customize how the main product image is replaced with the design preview.
cartImageFallback(item, rowEl, images, originalUrl)Take over cart-page thumbnail replacement when the default doesn't fit your markup.
cartJSImageFallback(item, itemEl, image, originalUrl, result) => resultSame for AJAX carts/drawers.
cartAfterUpdate()After a cart update on the cart page.
cartBeforeCheckout()After the checkout button was clicked (best-effort; not guaranteed on all themes).

Bulk order module (FPD.bulkOrder)​

Settings for the designer's bulk order module, set inline before the bundle loads like FPD.callbacks.

window.FPD = window.FPD || {};
window.FPD.bulkOrder = {
gridOption: ['Size', 'Storlek'],
discountTiers(product) {
return [
{ quantity: 10, type: 'percentage', value: 10 },
{ quantity: 50, type: 'percentage', value: 20 },
];
},
};
KeyTypePurpose
gridOptionstring | string[]The option the quantity grid spans, by name (case-insensitive; the first that matches). Default: the product's last option.
discountTiers(shopifyProduct) => tiers | nullThe volume discount tiers to show the order with (see below).
priceFactor(shopifyProduct) => numberThe factor the module shows its prices at, e.g. 1.25 where the Shopify prices are net and the theme shows them with 25 % VAT (see below). Default: 1.

discountTiers​

The module only shows the discount. Your discount app still takes it in the cart, so the tiers you return have to be the ones it applies.

  • Called synchronously on every price calculation (module opened, quantity changed, design price changed) with the Shopify product the rows are built from. While your discount app has not loaded yet, return null; the tiers are picked up on the next calculation.
  • Returns [{ quantity, type, value }]. quantity is the number of pieces from which the tier applies. Only type: 'percentage' exists so far: value percent off.
  • The tier is chosen by the order's total number of pieces, across all variants. The percentage is taken off the variant price plus what the design adds, rounded to whole cents per piece.
  • Tiers with an unknown type, or a quantity/value that is not a positive number, are ignored, and percentages are capped at 100. If the callback throws, the order is shown at full price and the error is logged once with console.debug.
  • The summary shows the full price struck through, a discount line and how many pieces are missing for the next tier. Texts come from the module translation keys bulk_order_discount ({percent}) and bulk_order_next_tier ({n}, {percent}).

For Deal Easy there is a ready-made snippet: see Deal Easy volume discounts.

priceFactor​

For themes that show prices other than the Shopify variant price - typically net prices in Shopify, shown with VAT by the theme. The module only shows the prices at the factor; the cart is still charged the variant price.

  • Called synchronously on every price calculation, like discountTiers. Every price the module shows is multiplied by it: the price per piece, the order lines, the total and the number on Done. Each piece is rounded to whole cents, and the volume discount is taken off before the factor.
  • Anything but a positive number is 1. If the callback throws, the prices are shown unchanged and the error is logged once with console.debug.
  • When the factor changes while the designer is open (the shopper switches the VAT mode), fire fpd:bulk-order:refresh-prices on document so the module recalculates.
window.FPD.bulkOrder = {
priceFactor() {
return window.getVatMode && window.getVatMode() === 'incl' ? 1.25 : 1;
},
};
document.addEventListener('vatmodechange', function () {
document.dispatchEvent(new CustomEvent('fpd:bulk-order:refresh-prices'));
});

Other useful globals​

  • FPD.additionalPrice — a flat surcharge added to every calculated price (number).
  • FPD.earlyLoadProduct — start loading the product JSON as early as possible.
  • FPD_EXT.productHash — alternative way to hand a saved-design hash to the page (instead of the ?_fpd-hash URL parameter).
  • FPD.debug / FPD.errorReporting — see Troubleshooting.