NAV

Add or modify features in storefront

Add custom JavaScript code

Example of custom JavaScript to modify storefront

/*
 * Show a promo 'Free shipping' message on the cart page. 
 * In the example below, users will see a message on the cart page 
 * informing them that they will qualify for free shipping if their 
 * order is more than $99
 */

var promoMessage = "Orders $99 and up ship free!";
var minSubtotal = 99;
var widgets;

// Calculating subtotal and displaying the message
var checkSubtotal = function(order) {
  if (order) {
    var subtotal = order.total - order.shipping;
    if (subtotal > minSubtotal) {
      alert(promoMessage);
    }  
  }
}

// Detecting whether we're on the cart page and get the cart info
Ecwid.OnPageLoaded.add(function(page) {
  widgets = Ecwid.getInitializedWidgets();

  // if storefront widget is present on this page
  for (i = 0; i < widgets.length ; i++) {
    if (widgets[i] == "ProductBrowser") {
      if ('CART' == page.type) {
        Ecwid.Cart.calculateTotal(function(order) {
          checkSubtotal(order);
        });
      }
    }
  }
});

// Get color value for the message and store it in color variable
var color = Ecwid.getAppPublicConfig(appId);

// your code here
// ...

As soon as your script is loaded on the page with Ecwid storefront, you can access the page DOM and do pretty much everything you want by means of native JavaScript or whatever framework you want. If you use a JS framework, please make sure it’s already loaded on the page by the moment you start using it.

In addition, Ecwid provides a JavaScript API that you can use to retrieve store information and track Ecwid events on the page. For example:

  • Ecwid.getOwnerId() returns the store ID. You may want to use it to identify which store your script is loaded in now
  • Ecwid.OnPageLoad() and Ecwid.OnPageLoaded() help you to track store page switch and identify which page is opened
  • Ecwid.Cart object and its methods allow to manage the customer cart
  • EcwidApp.getAppPublicConfig will return store-specific data from application storage

More details: Ecwid JavaScript API

How to load custom JavaScript anytime storefront is loaded

Ecwid API allows you to do the same in more convenient way: you simply specify the URL of file with your custom JavaScript code and Ecwid automatically loads that code in the user storefront. So you don’t need to put the JS on merchant site manually or ask them to do that.

In more details:

  1. After your app is registered, contact us and provide the https URL of the .css and/or .js file you’d like to load in the user storefront.
  2. When asking a user to install your app, Ecwid will request the customize_storefront permission from them. (If your app is for a specific store, make sure to add customize_storefront scope in the OAuth process.)
  3. The next time the user storefront is loaded in any browser or website, the specified external JS/CSS files will be automatically appended, loaded, and executed on that page.

Q: How to know what Ecwid widgets are on a page?

If your applcation customizes storefront, your script will be loaded at all times when app.ecwid.com/script.js?{store_id} is on a page. It means that if a simple search widget is present on a page, your script will be executed.

Ecwid widgets can be also embedded in many ways:

  • as a part of a website page
  • in an iframe
  • certain widgets are displayed only (like search and minicart, no storefront)

So, it is important to know where exactly your application is loaded: if there is a storefront present on a page or if it’s just a search widget. To check that, use Ecwid.getInitializedWidgets() function of Ecwid Javascript API. Using it, you can determine whether your app functionality needs to be initialized or not.

Q: What is the best way to add new scripts from my code?

Add external script to the page example

var s = document.createElement("script");
s.type = "text/javascript";
s.src = "https://example.com/example.js";
document.head.appendChild(s);

In case if you need more than one JavaScript code executed on a page, you can load additional scripts from within your base app JavaScript code.

We recommend that you load external JS files using a standard function createElement(). See example code on the right. It allows you to create a new <script> element on a page with the parameters you need and then append it to the DOM tree to get loaded and executed.

More details about this approach: W3CSchools

Store-specific custom JavaScript

Example of the script that dynamically loads store-specific code

// Load external script with store
function loadConfig(ecwidStoreId, callback) {
  var script = document.createElement("script");
  script.setAttribute("src", '//example.com/myapp/store' + ecwidStoreId + '.js');
  script.charset = "utf-8";
  script.setAttribute("type", "text/javascript");
  script.onreadystatechange = script.onload = callback;
  document.body.appendChild(script);
}

// Application functionality
function doCoolStuff() {
  //...
}

// Get color value for the message and store it in color variable
var color = Ecwid.getAppPublicConfig(appId);

// Get Ecwid store ID and start working
loadConfig(Ecwid.getOwnerId(), doCoolStuff);

In most cases, your application behavior will vary depending on the store it is opened in. Although Ecwid API allows you to specify only one JS file per application, your application can detect the current Ecwid store ID and act correspondingly. Use the Ecwid.getOwnerId() method to detect the user store ID in your script.

For example, let’s say you need to dynamically add a store-specific configuration to your script when it’s executed in some particular storefront. You can detect the store ID in your script and call a script on your server containing the store-specific code.

To get information for that specific store you can use Ecwid.getAppPublicConfig function in Ecwid Javascript API. See more details on how to access that data in Application data section of documentation.

Caching JavaScript file contents

When your external JS file is loaded on a page, it is loaded like any other resource via a GET request by a web browser. If you’d like to use caching to increase the loading speeds of your script, we can suggest several options:

  • invalidate cache for your JS file link when deploying a new version
  • in your JS file, place a code that will get the latest JS assets file from your server dynamically and append it to a page (instead of the using an actual code of your app on that URL)
  • don’t use caching, so that your files for storefront are always up-to-date for any user

Using jQuery on store pages

Checking for jQuery on a page example

// function to load jQuery

function loadjQuery(){
  var jq = document.createElement('script'); jq.type = 'text/javascript';
  jq.src = 'https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.2.js';
  document.getElementsByTagName('head')[0].appendChild(jq);
}

if (typeof jQuery == 'undefined') {  
  loadjQuery();
} else {}

// your app code
// ...

jQuery is a very popular JavaScript library that is used in many websites. The developers of themes for Wordpress CMS, for example, include this library right into the theme to have access to its functions and to operate various HTML elements on the page easily.

Ecwid storefronts can be customized in many ways, for example: you can set specific behaviour for each page or each user that visits those pages. Some developers prefer using native JavaScript functions to change the position or the display of certain elements. But many use different versions of popular jQuery library.

To ensure that your jQuery version code doesn’t conflict with other applications that change Ecwid storefront, please see our guidelines:

For simple modifications

When your modifications don’t require specific versions of jQuery loaded on a page and are fairly simple, we suggest you follow this algorithm:

First, check for jQuery object on current page. If no object is defined, load any jQuery version you prefer using the example code on the right. If there is already jQuery object available - skip the loading and use the curreny jQuery on this page.

For complex modifications

When you are using advanced jQuery’s features such as jQuery UI, version specific functions, etc. it will be hard to work with, if a website already has varuous jQuery versions on a page. To avoid any version conflicts with current page jQuery version, we suggest you use jQuery noconflict feature. Check out how it works: https://api.jquery.com/jquery.noconflict/

Center popups in iframe storefronts

Example of centering popups

<script src='https://d1e443hvef5jf2.cloudfront.net/static/iframeintegration.js'></script>
<script type='text/javascript'>

window.addEventListener('load',  function(e) {
  setPopupCentering('#myframe');
});

</script>

Ecwid can be embedded to a website in many ways. Sometimes a storefront can be inserted in an iframe container due to the limitations of a platform. To make sure that all popup windows such as customer account login popup are displayed in the center of an iframe, use the example code on the right in a main frame of your page.

setPopupCentering() function accepts one argument, which is the ID of an iframe element, where Ecwid storefront is loaded. In order to work, setPopupCentering() function needs to have iframeintegration.js file loaded for that frame.

Custom URL redirect after online purchase

Setting custom URL redirect after online purchase

<script>
window.ec = window.ec || Object();
window.ec.config = window.ec.config || Object();
window.ec.config.custom_redirect_after_purchase = 'YOUR CUSTOM URL HERE';
</script>
<script>
window.ec = window.ec || Object();
window.ec.config = window.ec.config || Object();
window.ec.config.custom_redirect_after_purchase = 'https://mycoolstore.com/thank-you.html';
</script>

Some merchants may want to send their customers after a successful online purchase to a custom URL. Using the configuration on the right you can set the URL where the customer should be redirected.

Important: the redirect will work only for online payment methods. For offline payment methods, consider using the Custom URL for 'Thank you’ page application.

Storefront JavaScript API

Any Ecwid storefront has a JavaScript API available at all times to help users create various customizations for their storefronts.

Its features include:

  • detect currently opened page details
  • set shipping and billing address for customer
  • get customer’s cart details
  • manage customer’s cart and others.

To find our more about it, plesae see the Storefront JavsScript API Documentation.

Using REST API in storefront

When working on a custom storefront functionality, applications can require getting up-to-date catalog information from Ecwid store.

Get 3 products from Ecwid REST API using JavaScript with public token

var xhttp = new XMLHttpRequest();
var storeId = 1003;
var token = 'public_qKDUqKkNXzcj9DejkMUqEkYLq2E6BXM9';

var requestURL = 'https://app.ecwid.com/api/v3/'+storeId+'/products?limit=3&token='+token;

xhttp.open("GET", requestURL, true);
xhttp.send();

xhttp.onreadystatechange = function() {
  if (xhttp.readyState == 4 && xhttp.status == 200) {
    var apiResponse = xhttp.responseText;
    console.log(apiResponse); // prints response in format of Search Products request in Ecwid API
  }
};

We suggest using public access token to get information about: store details, enabled products, enabled categories, combinations of enabled products, visible product types and deleted items statistics on demand with Ecwid REST API. Check out example on how to do this on the right.

With public access token you can safely make requests to Ecwid REST API without creating a buffer in a form of a server-side code, which requested information for your client-side code. You can make an Ajax request to Ecwid API with your JavaScript code and have a completely serverless application.

Access merchant in-app preferences

Applications can work and look differently in various stores, so you can provide tailored user experience to the store owner and a website they have in your application.

App public config allows apps to access user specific data in storefront as soon as it starts to load, so no calls to external servers are required and result is available right away. It’s recommended that you use app storage to access public user data in storefront area of your application.

How it works:

  1. App saves public data in public storage in backend
  2. App gets public data from public storage in storefront
  3. App tailors user experience to merchant settings

For example, using this method you can pass store ID to a storefront, category or product ID where the changes need to apply or whether your widget needs to be shown in storefront.

To find out more about this process, please check Public App Config section.