Automatic event triggers

Storefront JS API can help you with developing storefront customizations. One of the most useful and often required tools is automatic triggers. Automatic triggers work like event handlers, calling the code inside when a specific event happens on the storefront. With event triggers, you don't have to write manually and test code for tracking events like page DOM load, customer login, customer cart change, etc.

The methods listed below require JS API to be loaded on the page. Read more on how to enable JS API.

Ecwid.OnAPILoaded()

This function triggers your code inside when Storefront JS API fully loads on the storefront page. It also ensures that the JS API is loaded before your code relying on it starts working. We recommend calling all JavaScript code related to the Ecwid storefront from inside this method.

Code example:

Ecwid.OnAPILoaded.add(function() {
    console.log("Ecwid storefront JS API has loaded");
});

Use case for other triggers and methods:

Ecwid.OnAPILoaded.add(function() {
    console.log("JS API is loaded");
    console.log("Ecwid store ID: "+Ecwid.getOwnerId());
    
    Ecwid.OnPageLoaded.add(function(page) {
        console.log("Page DOM is loaded");
        console.log("Page type is: "+page.type)
    });
});

// prints
// 
// JS API is loaded
// Ecwid store ID: 15695068
// Page DOM is loaded
// Page type is: SITE

When this method triggers, the website DOM is not yet loaded, so use it to load scripts that don't rely on specific page content.

Ecwid.OnPageLoad

This event runs when the page DOM is loaded. Please note that it doesn't wait for the Ecwid product browser to fully load.

Code example:

Ecwid.OnPageLoad.add(function() {
    console.log("Page DOM has just loaded");
});

Ecwid.OnPageLoaded

This method is different from the OnPageLoad. It runs when the page DOM with the Ecwid product browser is loaded and is ready for customization.

It contains a callback function with page argument containing information about a loaded page.

Code examples:

Ecwid.OnPageLoaded.add(function(page){
  console.log(JSON.stringify(page));
});

// prints
// 
// {
//   "type":"PRODUCT",
//   "categoryId":0,
//   "hasPrevious":false,
//   "mainCategoryId":0,
//   "name":"Desk Black 101x50x76.5 cm Engineered Wood",
//   "nameTranslated":{
//     "cs":"",
//     "en":"Desk Black 101x50x76.5 cm Engineered Wood"
//   },
//   "productId":561386461
// }
Ecwid.OnPageLoaded.add(function(page) {
    if (page.type == "CART") {
      // do something ...
  }
});

page callback fields

NameTypeDescription
typestringPage type. Available values:
SIGN_IN - Sign in page for customers.
ACCOUNT_SETTINGS - Main customer account page.
ORDERS - Page where customers can see their order history.
ACCOUNT_SUBSCRIPTION - Page where customers can see their subscription products.
ADDRESS_BOOK - Page where customers can see their saved addresses page.
FAVORITES - Page where customers can see products added to favorites.
RESET_PASSWORD - Page where customers can reset their account password.
CATEGORY - Any category page.
PRODUCT - Any product page.
SEARCH - Products search page.
CART - Cart page, first page of the checkout.
CHECKOUT_ADDRESS - Checkout page where customers enter their address for delivery.
CHECKOUT_DELIVERY - Checkout page where customers choose shipping/pickup option.
CHECKOUT_ADDRESS_BOOK - Checkout page where customers select one of the saved addresses.
CHECKOUT_PAYMENT_DETAILS - Checkout page where customers select payment option
ORDER_CONFIRMATION - Checkout page customers see after placing an order. Sometimes referred to as the "Thank you for order" page.
ORDER_FAILURE - Page customers see in case of failed payment.
DOWNLOAD_ERROR - Page customers see in case of failed file download (for digital products only).
namestringName of the opened category or product. Available for CATEGORY and PRODUCT page types.
nameTranslatedarrayTranslated name of the currently opened product. Available for PRODUCT page type.
keywordsstringKeywords for searching orders on the customer account page or products on the product search page. Available for CATEGORY, and SEARCH page types.
offsetOffset for the current list of orders or products on the page starting from 0. Available for SEARCH, and CATEGORY page types.
categoryIdintegerCategory ID. If categoryId == 0, it's a root category. Available for CATEGORY page type.
mainCategoryIdintegerDefault category ID for the product. Available for PRODUCT page type.
sortstring, Sorting tye. Available values:
normal - Default product sorting from store settings.
relevance - Most relevant to search criteria products first.
addedTimeDesc - New products first.
priceAsc - Sort products by price (from low to high).
priceDesc - Sort products by price (from high to low).
nameAsc - Sort products by name (from A to Z).
nameDesc - Sort products by price (from Z to ).

Available for SEARCH and CATEGORY page types.
orderIdintegerID of a placed order. Available for ORDER_CONFIRMATION page type.
orderNumberintegerOutdated field, use orderId instead. Internal ID of a placed order (still can be used in REST API requests). Available for ORDER_CONFIRMATION page type.
vendorOrderNumberstringOutdated field, use orderId instead. Internal ID of a placed order (still can be used in REST API requests). Available for ORDER_CONFIRMATION page type.
errorTypestringType of error when digital product download has failed. Available values:
expired - Download link expired.
invalid - Download link is incorrect
limit - Number of maximum allowed downloads for the link has been reached.

Available for DOWNLOAD_ERROR page type.
keyintegerInternal product file ID. Available for DOWNLOAD_ERROR page type.
productIdintegerProduct ID. Available for PRODUCT page type.
variationIdnumberProduct variation ID. Available for PRODUCT page type.
filterParamsarray{FilterParameters}Filter parameters used in a product search. Available for SEARCH and CATEGORY page types.

FilterParameters

NameTypeDescription
attributesarraySelected attributes for product search.
optionsarraySelected options for product search.
categoriesarraySelected category IDs for product search.
includeProductsFromSubcategoriesbooleanDefines if the search includes products from subcategories of selected categories. Available values:
true - Search includes subcategories.
false - Search doesn't include subcategories.
keywordstringKeyword used for product search.
inventorystringDefines if the search includes only products "in stock" (with stock more than 0). Available values:
instock - Search includes only "in stock" products.
"" - Search also includes "out of stock" products.
hasPreviousbooleanTells if a customer visited other store pages before this one. Available values:
true - This is not an entry page.
false This is an entry page for the customer.

Ecwid.OnSetProfile

This method allows tracking when customers log in and out on the storefront. It contains a callback function with customer argument when a customer logs in, and null if a customer has logged out.

Code example:

Ecwid.OnSetProfile.add(function(customer){
	console.log(customer.email);
})

// prints
// "[email protected]"

Ecwid.OnCartChanged

This event allows tracking any cart changes excluding the payment method selection. It contains a callback function with a cart argument, that has information about the cart after the change.

Code example:

Ecwid.OnCartChanged.add(function(cart){
    console.log(JSON.stringify(cart));
});

// prints
// 
// {
// 	"id":"TJ6VG",
// 	"cartId":"99E7E224-5F6F-4C00-BFE9-9F72F2B5A471",
// 	"orderId":506524300,
// 	"items":[...],
// 	"productsQuantity":4,
// 	"shippingMethod":"Standard shipping",
// 	"shippingPerson":{},
// 	"weight":4
// }

Full list of Ecwid.OnCartChanged event triggers :

  • Cart is initialized, synced or cleared
  • Product added, updated (increased quantity, changed selected options) or removed
  • Discount coupon or discount is applied or removed
  • Shipping address is added or updated
  • Shipping method is selected or changed

Ecwid.OnProductOptionsChanged

This event allows tracking of changed product options on product pages. It contains a callback function with productid argument, containing the ID of the changed product. Only storefront V3 supports all product option types. Check the storefront version with this method.

Code example:

Ecwid.OnProductOptionsChanged.add(function(productid) {
   console.log("Options changed, product id: " + productid);    
});

// prints
// Options changed, product id: 123456

Ecwid.OnOrderPlaced

This event allows tracking placed orders on the storefront and receiving order details in a callback function with an order argument.

Code example:

Ecwid.OnAPILoaded.add(() => {
    Ecwid.OnOrderPlaced.add((order) => {
        console.log(order.total);
    });
});

// prints
// 829

order callback argument

NameTypeDescription
itemsArray{OrderItems}Details about products in order.
productsQuantitynumberTotal quantity of products in order.
weightnumberTotal order weight.
paymentMethodstringSelected payment method name. undefined if no method is selected.
shippingMethodstringSelected shipping method name. undefined if no method is selected.
shippingCarrierNamestringSelected shipping carrier name. undefined if no method is selected.
totalnumberOrder total cost including subtotal, discounts, coupons, taxes, fees, and shipping.
totalWithoutTaxnumberOrder total without taxes.
subtotalnumberOrder subtotal (product cost before shipping cost applied).
subtotalWithoutTaxnumberOrder subtotal without taxes.
taxnumberOrder total tax.
couponNamestringApplied discount coupon name. undefined if no discount coupon is applied.
couponDiscountnumberValue of coupon discount applied to order.
volumeDiscountnumberValue of discount applied to subtotal (doesn't include discount coupon).
customerGroupDiscountnumberDiscount based on customer group.
discountnumberTotal discount applied to order.
shippingnumberOrder shipping cost.
shippingWithoutTaxnumberOrder shipping cost without taxes.
handlingFeenumberOrder handling fee.
handlingFeeWithoutTaxnumberOrder handling fee without taxes.
shippingAndHandlingnumberSum of shipping and handlingFee fields
billingPersonarray{PersonInfo}Customer billing address
shippingPersonarray{PersonInfo}Customer shipping address
affiliateIdstringAffiliate ID used in order.
orderNumbernumberInternal order ID. Use ID from vendorNumber instead.
vendorNumberstringOrder ID. Matches order id in REST API and customer emails.
datestringOrder creation datetime in UNIX timestamp, for example, "1484638550".
paymentStatusstringPayment status of an order. Available values: AWAITING_PAYMENT, PAID, CANCELLED, REFUNDED, PARTIALLY_REFUNDED, INCOMPLETE
fulfillmentStatusstringFulfillment status of an order. Available values: AWAITING_PROCESSING, PROCESSING, SHIPPED, DELIVERED, WILL_NOT_DELIVER, RETURNED, READY_FOR_PICKUP
customerarray{CustomerInfo}Customer's email and name.
extraFieldsarray{OrderExtraFieldsInfo}Order extra field details.

OrderItems

NameTypeDescription
quantitynumberQuantity of this product in order.
productarray{ProductInfo}Product details.
optionsarraySelected product options.

ProductInfo

NameTypeDescription
idIntegerProduct ID.
nameStringProduct name.
priceIntegerProduct price.
shortDescriptionStringProduct description truncated to 120 characters.
skuStringProduct SKU.
urlStringLink to a product page.
weightIntegerProduct weight.

PersonInfo

NameTypeDescription
namestringCustomer's name.
phonestringCustomer's phone number.
companyNamestringCustomer's company name.
streetstringAddress: street.
citystringAddress: city.
countryNamestringAddress: country name.
countryCodestringAddress: country code.
stateOrProvinceNamestringAddress: state name.
stateOrProvinceCodestringAddress: state code.
postalCodestringAddress: zip code.

CustomerInfo

NameTypeDescription
namestringCustomer's name.
emailstringCustomer's email.

OrderExtraFieldsInfo

NameTypeDescription
orderBynumberSorting position for order details page in Ecwid admin. Starts with 0 (highest position).
titlestringExtra field name.
orderDetailsDisplaySectionstringSection where the extra field is displayed.
typestringExtra field type.
valuestringExtra field value.

Ecwid.OnPageSwitch

This method allows tracking and preventing page switches on the storefront. It is triggered when a user is about to switch a page. The method works synchronously and contains a page argument in its callback function.

Use it to identify the page where users go and prevent page loading by returning a false value.

Code example:

Ecwid.OnPageSwitch.add(function(page) {
    if (page.type === "PRODUCT") {
        window.location.href = "index.html?type=product&id=" + page.productId
        return false
    } else if (page.type === "CATEGORY") {
        window.location.href = "index.html?type=category&id=" + page.categoryId
        return false
    }
})

window.instantsite.onTileLoaded

Ecwid Instant Site dynamically loads and unloads its sections depending on what customers currently see. This method allows you to call your JS code when a specific section (called "tile" in the function) is loaded.

Code example:

document.addEventListener("DOMContentLoaded", function() {
	window.instantsite.onTileLoaded.add(function (tile) {
		if (tile === 'tile-id') {
			document.getElementById("tile-id").innerHTML = '<iframe src=""></iframe>'; //add custom iframe
		}
	});
});

window.instantsite.onTileUnloaded

Ecwid Instant Site dynamically loads and unloads its sections depending on what customers currently see. This method allows you to call your JS code when a specific section (called "tile" in the function) is loaded.

document.addEventListener("DOMContentLoaded", function() {
	window.instantsite.onTileUnloaded.add(function (tile) {
		if (tile === 'tile-id') {
			document.getElementById("tile-id").innerHTML = ''; //remove Custom iframe
		}
	});
});