Web tracking - Javascript

Integrating your business with Exponea is the first step in getting closer to your customers. Once integrated, you will immediately start getting data about your customers' behavior. If you need any assistance in deciding which API is the best for your business, please contact our integration specialist.

Integration through JavaScript is recommended for a business based on web-browsing or for a business coded in other languages that still make use of JavaScript.

Basic integration

To integrate with Exponea using JavaScript, you need to copy-paste the following initialization code into the header of your webpage. This step is an essential prerequisite for identifying your customers and tracking their actions.

<script type="text/javascript">!function(i,t){function e(e){return function(){var n=arguments;if("initialize"==e&&n&&n[0].modify&&n[0].modify.overlay&&"loading"==t.readyState){var a="__inf__overlay__";t.write('<div id="'+a+'" style="position:absolute;background:#fff;left:0;top:0;width:100%;height:100%;z-index:1000000"></div>'),setTimeout(function(){var e=t.getElementById(a);e&&t.body.removeChild(e),i.exponea.__=!0},n[0].modify.delay||500)}this._.push([e,arguments])}}if(!i.exponea){var n,a,o="initialize identify update track trackLink trackEnhancedEcommerce getHtml showHtml showForm ping getAbTest".split(" "),r=t.createElement("script"),d="https:"===t.location.protocol?"https:":"http:";for(i.exponea={_:[]},a=0;a<o.length;a++)n=o[a],i.exponea[n]=e(n);r.type="text/javascript",r.async=!0,r.src=d+"//api.exponea.com/js/exponea.min.js",t.getElementsByTagName("head")[0].appendChild(r)}}(window,document);</script>
<script type="text/javascript">
    exponea.initialize({
        token: 'PROJECT TOKEN'
    });
</script>

This will initialize Exponea with your project token (your unique project identifier) so that every action will be tracked into your project correctly. You can find your project token in Settings > Project settings. This code must be included in every page where you want to track actions of your customers.

👍

Checking if you initialized Exponea correctly

After copy-pasting the initialization code, open your web business in a new window and visit a few pages. Then go to Data & Assets > Data Manager > Events and look for a green dot next to the page_visit event.

As you can see in the example below, the initialize call takes one argument, which is a config object. The basic config object is generated for you and it includes your project token and basic tracking options.
The customer parameter in initialize can take object with named identifiers same as exponea.identify() .

{
  target: DEFAULT_TARGET, //path to the Exponea instance API
  token: null, //project token
  customer: {}, //customer's attributes
  utm_always: false, //add UTM params to default, automatically tracked event properties?
  ping: {
    enabled: true, //enable session ping? By setting to FALSE, you disable session_start and sesion_end events
    interval: 2 * 60, //session ping interval in seconds
    properties: {} //add custom properties to session_ping event
  },
  lazy_merge: false,
  track: {
    auto: true, //enable automatic tracking set up in Data Manager -> Automatic Web Tracking?
    visits: false, //automatically track page visits?
    activity: false, //enable checking of user being active by events like mousedown, keydown,... and track user_active event
    unloads: false, //enable tracking user unloading the page and tracking web_unload event
    exits: true, // enable Exponea to automatically track clicking on link elements with data-exponea-track attribute set and creating a web_exit event with current and target location as attributes. You can also define it as a custom function
    default_properties: {}, //define custom properties to track with every event
    google_analytics: true //enable customer identification by their GA id
  },
  webOptimization: { // enable or disable specific web optimization features, can be set to true/false/following configuration object
    experiments: true, // experiments are applied by default
    webLayers: true, // web layers are enabled by default
    tagManager: true // tag manager is enabled by default
  },
  cookies: {
    cross_subdomain: true, //by default, the cookies are valid on both domain and all subdomains. If you want to restrict cookies only for current (sub)domain, set this attribute to false. You can also set it to String, manually defining the domain for cookies
    retrieve_callback: null //define a function that triggers on setting a customer's cookie in initialization
  },
  track_hash_changes: true, //handle hash URL change as a new page? Useful, if you have a single-page application and do not want to trigger all tracking, banners, ... on every hash change
  transfer_identity: true, //enable transfer of identity, from email links for instance
  debug: false //show debug logs in console?
}

Events

In Exponea, we distinguish between two types of events: system and custom ones. System events are automatically tracked across all projects. You can find their comprehensive list in the System events article. Custom events are the ones specifically-tailored integration for each project and you can choose whether to incorporate them. You can find some of them with examples of how to track them below. However, if you are looking for a more extensive list go to the Custom events article.

📘

Deduplication of events

Every tracked or imported event is checked for possible deduplication. Read more here.

Purchase

The purchase event tracks the basic purchase transaction of your customers. It is crucial for analyzing the overall performance of your business, evaluating campaigns, calculating the lifetime value of your customers and much more.

Overview of basic recommended attributes to track:

Attribute nameTypeValue / Description
purchase_statusstringsuccess / fail
product_listlist - JSON (Array of objects)List of all purchased products
total_pricenumberTotal value of the order
payment_typestringcash / card / bank_transfer...
<script type="text/javascript">
    exponea.track('purchase', {
        purchase_status: 'success',
        product_list: [ {product_id: "abc123", quantity:1} ],
        total_price: 7.99,
        payment_type: 'credit_card',
        ...
    });
</script>

Purchase_item

purchase_item events are generated alongside every purchase event and are related to every item ordered within that purchase. For example, if a customer buys 1 unit of product A and 2 units of product B within one purchase, then a single purchase event and two purchase_item events are generated.

Overview of basic recommended attributes to track:

Attribute nameTypeValue / Description
purchase_statusstringsuccess / fail
product_idstringUnique ID of the product
pricenumberPrice of 1 unit of the product
total_pricenumberTotal price paid for all units of this product
titlestringHuman-readable name of the product
quantitynumberNumber of items of this product bought
category_1stringTop level category name (human-readable)
<script type="text/javascript">
    exponea.track('purchase_item', {
        purchase_status: 'success',
        product_id: 123456,
        price: 90,
        total_price: 180,
        title: 'product name',
        quantity: 2,
        category_1: 'category name',
        ...
    });
</script>

Cart_update

Event cart_update is tracked whenever customers add or remove a product from the shopping cart. This event is mainly used in the abandoned cart email campaign.

Overview of basic recommended attributes to track:

Attribute nameTypeValue / Description
product_listlist - JSON (Array of objects)List of all products in the cart after the last update
total_quantitynumberNumber of products in the cart
total_pricenumberTotal value of the cart
actionstringadd / remove
product_idstringUnique ID of the updated product
titlestringHuman-readable name of the updated product
pricenumberPrice of the updated product
category_1stringTop level category of the updated product
<script type="text/javascript">
    exponea.track('cart_update', {
        action: 'add',
        product_list: [{item_id: "1234", item_quantity:3}, {item_id: "2345", item_quantity:2}],
        total_quantity: 2,
        total_price: 123.45,
        price: 54.99,
        title: 'Toy toy',
        category_1: 'Party toys'
        ...
    });
</script>

View_item

Event view_item tracks every view of a product page, which allows you to know how many users are interested in each product.

Overview of basic recommended attributes to track:

Attribute nameTypeValue / Description
product_idstringUnique ID of the product
titlestringHuman-readable name of the product
pricenumberPrice of 1 unit of the product
category_1stringTop level category name (human-readable)
brandstringBrand of the item
<script type="text/javascript">
    exponea.track('view_item', {
        product_id: '123456',
        price: 123,
        title: 'Lenovo ThinkPad',
        brand: 'Lenovo',
        category_1: 'Notebooks',
        ...
    });
</script>

View_category

Event view_category tracks every view of a category page. This information is useful when determining what are the most visited categories.

Overview of basic recommended attributes to track:

Attribute nameTypeValue / Description
category_idstringUnique identifier of the category
category_namestringHuman-readable name of the category
<script type="text/javascript">
    exponea.track('view_category', {
        category_id: '123456',
        category_name: 'Notebooks'
        ...
    });
</script>

Checkout

Event checkout is used to track several steps of the purchase process, including the customer data acquisition, payment, shipping, and the transaction thank-you page. Tracking these steps is vital for analyzing where customers drop out.

Overview of basic recommended attributes to track:

Attribute nameTypeValue / Description
step_numbernumberStep of the checkout process
step_titlestringHuman readable checkout process step title
<script type="text/javascript">
    exponea.track('checkout', {
        step_number: 2,
        step_title: 'Shipping details'
        ...
    });
</script>

Registration

Event registration is tracked when a new user registers on the website. This event allows you to keep track of customer behavior or trigger automated marketing campaigns. In combination with the 'exponea.update' function, the attributes this event tracks will be attributed directly to the customer profile.

Overview of basic recommended attributes to track:

Attribute nameTypeValue / Description
emailstringLower-cased and trimmed email address
first_namestringFirst name
last_namestringLast name
phonestringInternational phone number format, such as +15417543010
<script type="text/javascript">
    exponea.track('registration', {
        email: '[email protected]',
        first_name: 'Gordon',
        last_name: 'Freeman',
        phone: '+15417543010',
        ...
    });
</script>

Tracking list attributes

It is possible to track list attributes, that is equivalent to JS array. It is possible to use Exponea list filters with list attributes, which is not possible with objects (as shown above in cart_update).

<script type="text/javascript">
    exponea.track('view_article', {
        tags: ["finance", "red", "..." ]
    });
</script>

Customer identification

To know your customers better, you need to identify them with a unique identifier, such as e-mail or username.

Automatic identification

Exponea automatically creates an anonymous customer when the method initialize() (e.g from Javascript SDK) is called for the first time on a device. These customers are identified by a generated cookie which means that subsequent sessions within a single device will be tracked to the same customer.

Multi-device identification

Apart from the automatic cookie tracking, Exponea also allows clients to track a single customer across more platforms or devices. Therefore we can, for example, connect events that customers make in the Android and iOS version of your business.

Hard IDs

We use the method identify(hard_id) to assign a hard ID (e.g. email address or username) to a user. When a customer with the given hard ID already exists, all customer profiles with the same ID will be merged. A new customer is created in Exponea every time a user is identified with a different hard ID. However, all previous events remain in the previous customer history.

Implementation

We can use the identify() method in two ways:

  • identify(hard_id);
    • identity field registered will be updated
  • identify({identity: id});
    • We can save various hard IDs for a customer. However, customers are merged under every hard ID. Therefore if two customers with different registered are identified with the same hard ID identity field, event tracking will fail.

A good practice is to identify customers after every successful login/registration. More frequent identification may lead to problems with customer merging.

Copy-paste the following snippet into the code where it is possible to identify the customer for the first time (for example right after login or registration) so that every event the customer creates from this point on will be tracked correctly and directly to them.

<script type="text/javascript">
    exponea.identify('[email protected]');
</script>

This will identify the customer with a username [email protected], which will now be the hard ID shown as registered in customer attributes. Without identification, events are added to anonymous customers. Please note that you don't lose any information about these events after you identify a customer – these events will be merged into a newly identified customer.

🚧

It is important to use a unique identifier, such as your internal database userID or email.
We also strongly recommend lower-casing and trimming the ID, which will improve the data quality.

Multiple identities

If there are more identities (more than registered and cookie) in the project, you need to use a special identify call.

For example to identify with email_id you call:

<script type="text/javascript">
    exponea.identify({ 
        email_id: "[email protected]" 
    });
</script>

If you are identifying a customer and you know all identities, you can also identify with:

<script type="text/javascript">
    exponea.identify({
        registered: "user_id_123", 
        email_id: "[email protected]" 
    });
</script>

🚧

If using caching on your web server, you need to make sure you do not insert the identify script into this part.

Updating the customer’s profile

In addition to tracked events, every customer in Exponea has a set of attributes. Attributes can be used to contact the customer through a personalized campaign. Copy-paste the following snippet into the code where you want to update customer attributes.

<script type="text/javascript">
    exponea.update({
        email: '[email protected]',
        first_name: 'Gordon',
        last_name: 'Freeman',
        company: 'Blackmesa',
        registration_date: '2014-04-10',
        ...
    });
</script>

This will update the customer attributes registration_date, email, first_name, last_name and company.

If a customer attribute doesn’t exist at the time the code is executed, the attribute will be created. Any customer attribute can be easily deleted later in the Data Manager.

🚧

Please note that even if you choose to set email as the hard ID, you still need to specify the customer attribute email. In campaigns, emails to customers are sent based on this attribute, which is independent of the hard ID.

This guide should have provided you with all the basics needed to start tracking your first events. We would love to help you get started as soon as possible, so if you have any questions, please contact our integration specialist.

Advanced tracking

Customizing default tracking

Default tracking behavior can be adjusted in the exponea.initialize(options) call:

<script type="text/javascript"> 
    exponea.initialize({
        token: 'PROJECT TOKEN',
        customer: 'Insert unique identified of your customer or remove this line (so cookie identification will used)',
        ping: { enabled: true}, // enables tracking session_start, first_session and session_end events
        track: { visits: true }  // enables tracking page_visit event
    });
</script>

You can also specify custom properties to be emitted with the session_start and session_end events.

<script type="text/javascript">
    exponea.initialize({
        token: 'PROJECT TOKEN',
        customer: 'Insert unique identified of your customer or remove this line (so cookie identification will used)',
        ping: {
            // specify your custom properties here
            properties: {
                version: 2,
                subdomain: 'www'
            }
        }
    });
</script>

📘

The customer parameter can use any object with identifier same as exponea.identify(). When string is used, it will use identifier registered only.

Action tracking

You can emit custom events when clicking links:

<a id="exponea_link" href="http://www.exponea.com">Exponea</a>

<script type="text/javascript">
    exponea.trackLink('#exponea_link', 'external_link', {
        site: 'Exponea'
    });
</script>

HTML campaigns

To display the content of your HTML campaign for the current user, use the following code:

<script type="text/javascript">
    exponea.showHtml('#content', 'Name of your HTML campaign node');
</script>

If you want to work with HTML yourself, use the getHtml method instead:

<script type="text/javascript">
    exponea.getHtml('Name of your HTML campaign node', function (html) {
        // Do anything you want with html.
    });
</script>

Limitations

Characters . and $ are not allowed to be used in JSON keys. However, they can be used as values.

Bot filtering

Exponea automatically filters out bot traffic which it can identify. This currently works by default and can’t be configured on project-level basis.

Exponea filtering:

If customer/events is tracked with Exponea web tracking, and the message includes user-agent header with patterns from this file, the message is automatically neglected. The message then isn’t stored within Exponea.

Javascript SDK

All functionalities in a detail are described in a Javascript SDK.

Updated about a month ago


Web tracking - Javascript


Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.


We rely on cookies

to optimize our communication and to enhance your customer experience. By clicking on the Accept and Close button, you agree to the collection of cookies. You can also adjust your preferences by clicking on Manage Preferences. For more information please see our Privacy policy.

Manage cookies
Accept & close

Cookies preferences

Accept & close
Back