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.
Enable JS API on the storefront
The methods listed below require JS API to be loaded on the page. Read more on how to enable JS API.
Ecwid.OnAPILoaded()
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
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
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
page
callback fieldsName | Type | Description |
---|---|---|
type | string | Page 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 optionORDER_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). |
name | string | Name of the opened category or product. Available for CATEGORY and PRODUCT page types. |
nameTranslated | array | An array of available translations for product or category names. Available for CATEGORY and PRODUCT page types. |
keywords | string | Keywords for searching orders on the customer account page or products on the product search page. Available for ORDERS , CATEGORY , and SEARCH page types. |
from | integer | The timestamp for searching orders date range (lower bound). Available for ORDERS page type. |
to | integer | The timestamp for searching orders date range (upper bound). Available for ORDERS page type. |
offset | Offset for the current list of orders or products on the page starting from 0. Available for ORDERS , SEARCH , and CATEGORY page types. | |
categoryId | integer | Category ID. If categoryId == 0 , it's a root category. Available for CATEGORY page type. |
mainCategoryId | integer | Default category ID for the product. Available for PRODUCT page type. |
sort | string, | 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. |
orderId | integer | ID of a placed order. Available for ORDER_CONFIRMATION page type. |
orderNumber | integer | Outdated field, use orderId instead. Internal ID of a placed order (still can be used in REST API requests). Available for ORDER_CONFIRMATION page type. |
vendorOrderNumber | string | Outdated field, use orderId instead. Internal ID of a placed order (still can be used in REST API requests). Available for ORDER_CONFIRMATION page type. |
errorType | string | Type of error when digital product download has failed. Available values:expired - Download link expired.invalid - Download link is incorrectlimit - Number of maximum allowed downloads for the link has been reached.Available for DOWNLOAD_ERROR page type. |
key | integer | Internal product file ID. Available for DOWNLOAD_ERROR page type. |
productId | integer | Product ID. Available for PRODUCT page type. |
variationId | number | Product variation ID. Available for PRODUCT page type. |
filterParams | array{FilterParameters} | Filter parameters used in a product search. Available for SEARCH and CATEGORY page types. |
FilterParameters
FilterParameters
Name | Type | Description |
---|---|---|
attributes | array | Selected attributes for product search. |
options | array | Selected options for product search. |
categories | array | Selected category IDs for product search. |
includeProductsFromSubcategories | boolean | Defines if the search includes products from subcategories of selected categories. Available values:true - Search includes subcategories.false - Search doesn't include subcategories. |
keyword | string | Keyword used for product search. |
inventory | string | Defines 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. |
hasPrevious | boolean | Tells 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
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
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
Ecwid.OnProductOptionsChanged
This event allows tracking of changed product options on product pages. It contains a callback function with productid
argument, containing ID of the changed product.
Code example:
Ecwid.OnProductOptionsChanged.add(function(productid) {
console.log("Options changed, product id: " + productid);
});
// prints
// Options changed, product id: 123456
Ecwid.OnOrderPlaced
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
order
callback argumentName | Type | Description |
---|---|---|
items | Array{OrderItems} | Details about products in order. |
productsQuantity | number | Total quantity of products in order. |
weight | number | Total order weight. |
paymentMethod | string | Selected payment method name. undefined if no method is selected. |
shippingMethod | string | Selected shipping method name. undefined if no method is selected. |
shippingCarrierName | string | Selected shipping carrier name. undefined if no method is selected. |
total | number | Order total cost including subtotal, discounts, coupons, taxes, fees, and shipping. |
totalWithoutTax | number | Order total without taxes. |
subtotal | number | Order subtotal (product cost before shipping cost applied). |
subtotalWithoutTax | number | Order subtotal without taxes. |
tax | number | Order total tax. |
couponName | string | Applied discount coupon name. undefined if no discount coupon is applied. |
couponDiscount | number | Value of coupon discount applied to order. |
volumeDiscount | number | Value of discount applied to subtotal (doesn't include discount coupon). |
customerGroupDiscount | number | Discount based on customer group. |
discount | number | Total discount applied to order. |
shipping | number | Order shipping cost. |
shippingWithoutTax | number | Order shipping cost without taxes. |
handlingFee | number | Order handling fee. |
handlingFeeWithoutTax | number | Order handling fee without taxes. |
shippingAndHandling | number | Sum of shipping and handlingFee fields |
billingPerson | array{PersonInfo} | Customer billing address |
shippingPerson | array{PersonInfo} | Customer shipping address |
affiliateId | string | Affiliate ID used in order. |
orderNumber | number | Internal order ID. Use ID from vendorNumber instead. |
vendorNumber | string | Order ID. Matches order id in REST API and customer emails. |
date | string | Order creation datetime in UNIX timestamp, for example, "1484638550" . |
paymentStatus | string | Payment status of an order. Available values: AWAITING_PAYMENT , PAID , CANCELLED , REFUNDED , PARTIALLY_REFUNDED , INCOMPLETE |
fulfillmentStatus | string | Fulfillment status of an order. Available values: AWAITING_PROCESSING , PROCESSING , SHIPPED , DELIVERED , WILL_NOT_DELIVER , RETURNED , READY_FOR_PICKUP |
customer | array{CustomerInfo} | Customer's email and name. |
extraFields | array{OrderExtraFieldsInfo} | Order extra field details. |
OrderItems
OrderItems
Name | Type | Description |
---|---|---|
quantity | number | Quantity of this product in order. |
product | array{ProductInfo} | Product details. |
options | array | Selected product options. |
ProductInfo
ProductInfo
Name | Type | Description |
---|---|---|
id | Integer | Product ID. |
name | String | Product name. |
price | Integer | Product price. |
shortDescription | String | Product description truncated to 120 characters. |
sku | String | Product SKU. |
url | String | Link to a product page. |
weight | Integer | Product weight. |
PersonInfo
PersonInfo
Name | Type | Description |
---|---|---|
name | string | Customer's name. |
phone | string | Customer's phone number. |
companyName | string | Customer's company name. |
street | string | Address: street. |
city | string | Address: city. |
countryName | string | Address: country name. |
countryCode | string | Address: country code. |
stateOrProvinceName | string | Address: state name. |
stateOrProvinceCode | string | Address: state code. |
postalCode | string | Address: zip code. |
CustomerInfo
CustomerInfo
Name | Type | Description |
---|---|---|
name | string | Customer's name. |
string | Customer's email. |
OrderExtraFieldsInfo
OrderExtraFieldsInfo
Name | Type | Description |
---|---|---|
orderBy | number | Sorting position for order details page in Ecwid admin. Starts with 0 (highest position). |
title | string | Extra field name. |
orderDetailsDisplaySection | string | Section where the extra field is displayed. |
type | string | Extra field type. |
value | string | Extra field value. |
Ecwid.OnPageSwitch
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
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
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
}
});
});