Tracking Setup: Distil Tracking Code

  • Updated

Distil uses JavaScript to collect data and send it in JSON data packets to Distil. This JavaScript code is the core of all Distil Tracking activity, whether you have installed Tracking via the Distil Shopify app or edited your website's HTML as described below.

This approach of adding a JavaScript code snippet to websites is used by many trusted platforms online, including Google Analytics, Facebook, Twitter, Pintrest and many others. It's a safe and widely used method of collecting Tracking data.

This article explains how to manually edit your site's HTML to add Distil JavaScript Tracking. If you haven't already, read our Introduction to Tracking for an overview of set-up options. If you have installed the Distil Shopify app then make sure you have completed the Tracking set-up for Shopify before making any further changes as described below. 

There are two steps to setting up Distil JavaScript Tracking:

  1. Install the Distil Distil JavaScript Tracking Code, and then
  2. Add Distil Event Tracking Calls to individual pages and events.

Install the Distil JavaScript Tracking Code

The Code

We've already written the code snippet for you, so you can just copy and paste it. The code is in Settings > Tracking > JS Bespoke tab. The script includes a unique 32-character identifier for your Distil Account, so take care not to modify this value.

Where To Put the Code

We recommend that the JavaScript code is inserted into the Head section of the HTML within each page on your website. This means that Distil Tracking will be initialised as soon as the page is loaded.

Alternatively, the JavaScript code can be included in the Body section. However, if users click away from the page before the JavaScript code initialises Distil Tracking, then this may result in some Tracking data being lost.

Adding the JavaScript Tracking code is straightforward if you're using a Content Management System (CMS) such as Wordpress, Squarespace, Magnolia or Weebly. Search online for instructions for your specific CMS.


Using the Code

Once the Tracking code is on a web page as described above, capturing Tracking data is a matter of calling the correct tracking event function at the correct time. The section below explains how to use the various functions, including the properties that they return.


Context Object

In addition to returning the properties of the called function, the JavaScript Tracking code will also automatically capture additional contextual information. This information includes the page that the user is on, their IP address, the referring URL and the time of the event. These pieces of information are stored in the Context object.

Here's an example of the Context object:

"Context”: {
   "DistilAccountId": "f1a2df172a8045489d95cf4658bd60ba",
   "AnonymousUserID": "598b0746-a073-4ac6-aa68-808ec3f6df68",
   "Device Information": "Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36",
   "EventTimestampUTC": "2021-04-13 16:26:12",
   "EventTimestampLocal": "2021-04-13 17:26:12",
   "PageTitle": "Product 2",
   "PageUrl": "http://www.fakesite.com/product-2",
   "ReferrerUrl": "http://www.fakesite.com/product-1",
   "IpAddress": "86.161.138.123"
}

The JavaScript Tracking code will automatically create a unique identifier called AnonymousUserID for each user visiting the site, and store this information in the browser's local storage (Distil does not use cookies). You can see this ID in the example object above. The same ID will be used to identify the user each time they visit, ensuring that the entirety of their behaviour is tracked and tied to a single Customer: from a first anonymous visit through to multiple purchases. For more information, read our article on how Distil identifies Customers.


Data Types

The following are the data types that are accepted by the Distil JavaScript Tracking code, in the JSON object property blocks.

Type Description Example
String Any combination of characters surrounded by double quotes (double quotes are always recommended rather than a single quote). There should not be any line return characters contained within the string. "Title" : "This is a string"
Boolean A true or false value – without quotes "Available" : true
Decimal A numerical value with a decimal point.  "Amount" : 12.34
Integer A numerical value representing a whole number "Age" : 23
Date (String) A DateTime represented as a string in the following format : yyyy-MM-dd HH:mm:ss "expirydate" : "2021-09-17 10:00:00"


Add Distil Event Tracking Calls

The following event functions are available in the Distil Tracking code:

Track Page

By default - each time a new page is loaded and the Distil tracking code is embedded in the page, then the trackPage function will be invoked automatically. This function will only pass the Context information for the current page. 

Call the trackPage function:

distil.trackPage();


Single Page Applications

For single page applications where the URL does not change, then by default the page does not reload, and therefore trackPage is not being called on each refresh. Therefore, it is up to the owner of the site to implement the call to this function each time the page changes.

Also - as the page URL does not change, then in order to track the virtual path, it is possible to pass in the path of the current page manually in the tracking like so:

distil.trackPage({pageUrl: '/newpath'});

There are some caveats around how this works and what is allowed to be entered into this property, as described in the section: Overriding Current Page Path

 

Identify Customer

When a user is browsing the site, their browsing history is tied to their AnonymousUserID. When this user identifies themselves explicitly by logging in or filling in a form with personal details, Distil captures this identifying information via the identifyCustomer event function and ties it to that person's browsing history via their AnonymousUserID (for more information, read our article on how Distil identifies Customers).

The identifyCustomer event function needs to be added to all pages where visitors identify themselves by logging in or filling in a form with personal details.

When this event function is called, the Distil Tracking code will also automatically pass a Context object as explained in the section above.

Call the event function:

distil.identifyCustomer(customerProperties, [additionalOptions]);

Pass the following argument to the function:

Argument Data Type Description
customerProperties JSON Object

A JSON Object containing all of the Customer properties that you wish to record, whether these are standard or custom. Distil will automatically try to recognise the properties sent based on the Property Name (see table below). Any properties that Distil does not recognise will be saved against the Customer and will be available within Distil as Custom Attributes.

additionalOptions JSON Object

See Additional Object Properties section below for further details


CustomerProperties Object properties

Note that customerProperties is required when using the identifyCustomer event function - and specific fields are required to be sent with each identifyCustomer request. A minimum of either the CustomerId OR the EmailAddress are required in order to identify the Customer to Distil (passing both is perfectly valid and encouraged if the CustomerId is unique) plus the current Marketing Subscribed status for the user.

Property Name Type Description Mandatory within identifyCustomer Mandatory within other functions
CustomerId String ID of the Customer Yes* Yes*
EmailAddress String Email Address for the Customer Yes* Yes*
GDPRStatus JSON GDPRStatus Object – see definition below for object properties below Yes No
FirstName String The Customer’s First Name No No
LastName String The Customer’s Last Name No No
FacebookSlug String The URI to the customer facebook profile No No
TwitterHandle String The URI to the customer twitter profile No No
InstagramHandle String The URI to the customer instagram profile No No
PostalAddress JSON PostalAddress Object – see definition below for object properties below No No


GDPRStatus Object properties

Note that some of the properties of GDPRStatus are mandatory.

Property Type Description Mandatory
MarketingSubscribed Boolean Whether the user has opted in  Yes
RightOfAccessRequested Boolean Whether the user has been asked to opt in  No
DataAnonymization Boolean Whether the user has asked for their data to be anonymised  No


PostalAddress Object properties

Property Type Description Mandatory
Line1 String Customer’s Address Line 1 No
Line 2 String Customer’s Address Line 2 No
Line 3 String Customer’s Address Line 3 No
Town String Customer’s Address Town No
Region String Customer’s Address Region No
Country String Customer’s Address Country No
Postcode String Customer’s Address Postcode No


Examples

Examples of a call with only mandatory fields:

1. With Customer ID

  let customerProperties = {
CustomerId: '1234',
GDPRStatus: {
  MarketingSubscribed: true / false
}
}

distil.identifyCustomer(customerProperties);

2. With Email Address

  let customerProperties = {
EmailAddress: 'user@yourcompany.com',
    GDPRStatus: {
      MarketingSubscribed: true / false
    }
  }

distil.identifyCustomer(customerProperties);

3. Or With Both CustomerID and Email Address

  let customerProperties = {
CustomerId: '1234,
EmailAddress: 'user@yourcompany.com',
GDPRStatus: {
MarketingSubscribed: true / false
}
}

distil.identifyCustomer(customerProperties);

Track Product

When a user views a single product page on the website, this information can be captured using the trackProduct event function, which needs to be added to all pages where this type of activity occurs.

When this event function is called, the Distil Tracking code will also automatically pass a Context object as explained in the section above.

Call the event function:

distil.trackProduct(productProperties, customerProperties, [additionalOptions]);

Pass the following arguments to the function:

Argument Data Type Description
productProperties JSON Object

A JSON Object containing all of the product properties that you wish to record, whether these are standard or custom. Distil will automatically try to recognise the properties sent based on the Property Name (see table below). Any properties that Distil does not recognise will be saved and will be available within Distil as Custom Attributes.

customerProperties JSON Object

A JSON Object containing all of the other Customer properties to record for this event. The customerProperties object is not mandatory and can be omitted, but if the object is supplied then at least one of the identifying properties for the Customer must be included (CustomerId or EmailAddress).

See the CustomerProperties Object properties section above for details of this object. Note that when used within this function, customerProperties does not support custom properties: any properties that do not match the standard Property Names will be discarded and not saved.

additionalOptions JSON Object

See Additional Object Properties section below for further details


ProductProperties Object properties

Note that some of the properties of ProductProperties are mandatory.

Property Name Type Description Mandatory
ProductId String The Product ID Yes
Name String The name of the Product Yes
Precis String The description of the product No
ThumbnailUrl String The URI to a thumbnail image for the product No
FullImageUrl String The URI to a full size image for the product No
ProductShopUrl String The URI to the product in the shop / store No
Categories String A comma delimited list of the categories the product belongs to No
Available Boolean A boolean indicating whether the product is currently available  No
ListPriceExTax Decimal The price of the product with no tax No
ListPriceIncTax Decimal The price of the product including tax No
Currency String The 3 letter currency code No
PriceBreaksDesc String This is only used in the case of building campaigns directly from this data so can be formatted as you wish No


Examples

Example of call with only mandatory fields:

let productProperties = {
 ProductId : 'Prod1234',
 Name: 'Product Name goes here'
}

distil.trackProduct(productProperties);

The customer property is not passed in the above as it is not mandatory.

Example of a call with Customer Properties included:

let productProperties = {
 ProductId : 'Prod1234',
 Name: 'Product Name goes here'
}

let customerProperties = {
 EmailAddress: 'joe@bloggs.com'
}

distil.trackProduct(productProperties, customerProperties);

Track Content

When a user views a Content page on the website, this information can be captured using the trackContent event function, which needs to be added to all pages where this type of activity occurs.

When this event function is called, the Distil Tracking code will also automatically pass a Context object as explained in the section above.

Call the event function:

distil.trackContent(contentProperties, customerProperties, [additionalOptions]);

Pass the following arguments to the function:

Argument Data Type Description
contentProperties JSON Object A JSON Object containing all of the content properties that you wish to record, whether these are standard or custom. Distil will automatically try to recognise the properties sent based on the Property Name (see table below). Any properties that Distil does not recognise will be saved and will be available within Distil as Custom Attributes.
customerProperties JSON Object

A JSON Object containing all of the other Customer properties to record for this event. The customerProperties object is not mandatory and can be omitted, but if the object is supplied then at least one of the identifying properties for the Customer must be included (CustomerId or EmailAddress).

See the CustomerProperties Object properties section above for details of this object. Note that when used within this function, customerProperties does not support custom properties: any properties that do not match the standard Property Names will be discarded and not saved.

additionalOptions JSON Object

See Additional Object Properties section below for further details


ContentProperties Object properties

Note that some of the properties of contentProperties are mandatory.

Property Name Type Description Mandatory
ContentId String The ID of the Content Yes
Title String The title of the Content Yes
ContentType String The Type of Content No
ThumbnailUrl String The URI to a thumbnail image for the content No
FullImageUrl String The URI to the full image for the content No
PublicUrl String The URI to the content  No
Precis String Description for the content No
PublishedOnUTC Date (String) Date of PublishingNeed to be in the format : 'yyyy-MM-dd HH:mm:ss' i.e. '2021-05-25 11:34:01' No
ExpiresOnUTC Date (String) Date the content expiresNeed to be in the format : 'yyyy-MM-dd HH:mm:ss' i.e. '2021-05-25 11:34:01' No
KeyWords String List of comma separated keywords for the content No
Available Boolean A boolean indicating whether the content is currently available  No


Examples

Example of call with only mandatory fields:

let contentProperties = {
ContentId: 'Cont1234',
  Title: 'Content Title goes here'
  }

  distil.trackContent(contentProperties);

The customer property is not passed in the above as it is not mandatory.

Example of a call with Customer Properties included:

let contentProperties = {
ContentId: 'Cont123',
Title: 'Content Title goes here'
};

let customerProperties = {
EmailAddress: 'joe@bloggs.com'
};

distil.trackContent(contentProperties, customerProperties);

Track Order

When a user places an order on the website, this information is captured using the trackOrder event, which needs to be added to all pages where this type of activity occurs.

When this event function is called, the Distil Tracking code will also automatically pass a Context object as explained in the section above.

Call the event function:

distil.trackOrder(orderProperties, customerProperties, [additionalOptions]);

 

Pass the following arguments to the function:

Argument Data Type Description
orderProperties JSON Object A JSON Object containing all of the order properties that you wish to record, whether these are standard or custom. Distil will automatically try to recognise the properties sent based on the Property Name (see table below). Any properties that Distil does not recognise will be saved and will be available within Distil as Custom Attributes.
customerProperties JSON Object

A JSON Object containing all of the other Customer properties to record for this event. The customerProperties object is not mandatory and can be omitted, but if the object is supplied then at least one of the identifying properties for the Customer must be included (CustomerId or EmailAddress).

See the CustomerProperties Object properties section above for details of this object. Note that when used within this function, customerProperties does not support custom properties: any properties that do not match the standard Property Names will be discarded and not saved.

additionalOptions JSON Object

See Additional Object Properties section below for further details


OrderProperties Object properties

Note that some of the properties of orderProperties are mandatory.

Property Name Type Description Mandatory
OrderId String The Order ID Yes
OrderLineItems JSON See OrderLineItems object definition below for the object properties. Yes
TotalOrderValueExTax Decimal This is the Total Order Value excluding any Tax. The value should be in the same Currency as specified in the Currency Attribute. No
TotalOrderValueIncTax Decimal This is the Total order Value including Tax.  No
PaymentMethod String Free text string for you to specify the Payment method. No
Currency String ISO Currency Code.  No
BillingAddress JSON Address Object – see definition below for object properties No
DeliveryAddress JSON Address Object – see definition below for object properties No

OrderLineItems Object Properties

Note that some of the properties of orderLineItems are mandatory.

Property Name Type Description Mandatory
OrderExternalId String The Order Id (same as the OrderId property in the OrderProperties object) Yes
ProductId String This should match a Product Id from the Product Data Yes
OrderLineItemId String The unique line item ID (can be a concatenation of the OrderExternalId and ProductId if the system does not have such a concept) No
Name String The Name of the product No
Url String URL to the Product page No
Qty Integer This is the Qty of the Product in this Line Item No
PriceExTax Decimal The price of the item excluding tax No
PriceInTax Decimal The price of the item including tax No
ThumbnailUrl String URL to the Product Thumbnail No
FullImageUrl String URL to the Product image in full No
Categories Array (String) An array of Categories for the product No


BillingAddress and DeliveryAddress Object properties

Property Type Description Mandatory
Title String Title of the Customer No
FirstName String First Name of the Customer No
LastName String Last Name of the Customer No
Line1 String Line 1 of the Address No
Line2 String Line 1 of the Address No
Line3 String Line 1 of the Address No
Town String Town/City for the address No
Region String Region of the address No
Country String Country for the Address No
Postcode String Postcode of the Address No
Phone String The Customer’s phone number No
Company String The name of the Company No

Examples

Example of call with only mandatory fields

let orderProperties = {
OrderId: 'Ord1234',
  OrderLineItems: [{
  OrderExternalId: 'Ord1234',
  ProductId: 'ABC-1234'
  }]
};

let customerProperties = {
EmailAddress: 'joe@bloggs.com'
};

distil.trackOrder(orderProperties, customerProperties);

Track Event

Sometimes you may wish to capture data on an event that doesn't fit into the standard Distil event functions described above. Distil supports custom Tracking data capture through the trackEvent event function.

Call the event function:

distil.trackEvent(eventName, eventValue, [eventCustomProperties], [customerProperties], [additionalOptions]);

Pass the following arguments to the function:

Argument Data Type Description
eventName String The name of the event - a short descriptive name that identifies the event.
eventValue Object A value for the event - this can be any value.
eventCustomProperties JSON Object A JSON Object containing all of the custom properties that you wish to record for this event. These will be saved and will be available within Distil as Custom Attributes.
customerProperties JSON Object

A JSON Object containing all of the other Customer properties to record for this event. The customerProperties object is not mandatory and can be omitted, but if the object is supplied then at least one of the identifying properties for the Customer must be included (CustomerId or EmailAddress).

See the CustomerProperties Object properties section above for details of this object. Note that when used within this function, customerProperties does not support custom properties: any properties that do not match the standard Property Names will be discarded and not saved.

additionalOptions JSON Object

See Additional Object Properties section below for further details


EventCustomProperties Object properties

As this event function records a custom event, this object contains only custom properties. The object must contain at least one property. Replace the Property Names (e.g. Property1) with your own custom names. 

Property Name Type Description Mandatory
Property1 String A custom property name and value pair. Yes
Property2 String A custom property name and value pair. No
Property3 String A custom property name and value pair. No
...      

 

Additional Object Properties

Overriding Current Page Path

Each of the functions mentioned above also have the option of overriding the current page path - to indicate that a user is on a different page to the one indicated in the URL.  This is especially useful for Single Page Applications where the URL does not change and the page does not fully reload as they navigate around the site.

To do this - a property called pageUrl needs to be passed in a JSON object block as the final parameter in the function call.

The format of the parameter to pass into the function calls is the same for each and looks as follows (several examples of different paths given - to show the flexibility of format allowed): 

{pageUrl : 'path-to-represent'}
{pageUrl : '/path-to-represent'}
{pageUrl : '/path/to/represent'}
{pageUrl : '/path/to/represent?QS=1'}
{pageUrl : 'https://website.com/path/to/represent?QS=1'}

If the path is specified without the domain at the beginning (perfectly valid) - then the current domain will be used and prepended to the path to create the full URL.

Therefore - the following 3 examples on the site www.testwebsite.com will produce the same URLs in the tracking :

{pageUrl : 'path-to-represent'}
{pageUrl : '/path-to-represent'}
{pageUrl : 'https://www.testwebsite.com/path-to-represent'}

Will all produce the path: https://www.testwebsite.com/path-to-represent
 

Query strings

Any query string values in the original path will also be preserved and appended to the end of the new URL.

Therefore - if the original URL is https://www.testwebsite.com?utm_source=google then the following will apply: 

Page Url Param Full result
{pageUrl : 'path-to-represent'} https://www.testwebsite.com/path-to-represent?utm_source=google
{pageUrl : '/path-to-represent'} https://www.testwebsite.com/path-to-represent?utm_source=google

 

Spoofing

While it is possible to specify a full path including website in the pageUrl parameter, we do not allow you to specify a different domain than the one the request is actually coming from.  This is to prevent spoof calls. If a parameter with a different domain is used, then it will be ignored and the original URL will be maintained in its place.

 

Examples for all tracking calls

trackPage 

let dataLayer = {
additionalProperties: {
pageUrl: 'new-path-for-request'
}
};

//Call track page - will pass all default contextual information for the page
distil.trackPage();

//Call track page with additional behaviour modification
distil.trackPage(dataLayer.additionalProperties);

identifyCustomer

let dataLayer = {
customerProperties: {
EmailAddress: 'joe@bloggs.com',
GDPRStatus: {
MarketingSubscribed: false
}
},
additionalProperties: {
pageUrl: 'new-path-for-request'
}
};

//Standard call
distil.identifyCustomer(dataLayer.customerProperties);

//With additional behavioural properties
distil.identifyCustomer(dataLayer.customerProperties, dataLayer.additionalProperties);

trackProduct

let dataLayer = {
productProperties: {
Name: "Test",
ProductId: "0001",
Available: true
},
customerProperties: {
EmailAddress: 'joe@bloggs.com',
GDPRStatus: {
MarketingSubscribed: false
}
},
additionalProperties: {
pageUrl: 'new-path-for-request'
}
};

//Only Product tracking info
distil.trackProduct(dataLayer.productProperties);

//No Customer info, but additional behavioural properties
distil.trackProduct(dataLayer.productProperties, {}, dataLayer.additionalProperties);

//With customer info as well
distil.trackProduct(dataLayer.productProperties, dataLayer.customerProperties, dataLayer.additionalProperties);

trackContent

let dataLayer = {
contentProperties: {
ContentId: 1,
Precis: 'some desc',
Title: 'Some Test Content',
},
customerProperties: {
EmailAddress: 'joe@bloggs.com',
GDPRStatus: {
MarketingSubscribed: false
}
},
additionalProperties: {
pageUrl: 'new-path-for-request'
}
};

//Only content tracking info
distil.trackContent(dataLayer.contentProperties);

//No Customer info, but additional behavioural properties
distil.trackContent(dataLayer.contentProperties, {}, dataLayer.additionalProperties);

//With customer info as well
distil.trackContent(dataLayer.contentProperties, dataLayer.customerProperties, dataLayer.additionalProperties);

trackOrder

let dataLayer = {
orderProperties: {
OrderId: "2345-2345",
TotalOrderValueExTax: 34,
Currency: "USD",
OrderLineItems: [{
OrderExternalId: "2345-2345-1",
ProductId: 23,
Qty: 32,
PriceExTax: 320.00
}]
},
customerProperties: {
EmailAddress: 'joe@bloggs.com'
},
additionalProperties: {
pageUrl: 'new-path-for-request'
}
};

//Only Order tracking info
distil.trackOrder(dataLayer.orderProperties, dataLayer.customerProperties);

//With additional behavioural properties
distil.trackOrder(dataLayer.orderProperties, dataLayer.customerProperties, dataLayer.additionalProperties);

trackEvent

let dataLayer = {
eventCustomProperties: {
size: 10
},
customerProperties: {
EmailAddress: 'joe@bloggs.com'
},
additionalProperties: {
pageUrl: 'new-path-for-request'
}
};

//Only Event info
distil.trackEvent('EventName', 'Event Value');

//Event info with additional properties
distil.trackEvent('EventName', 'Event Value', dataLayer.eventCustomProperties);

//Event info with additional properties and additional behavioural properties
// NOTE: Need the empty brackets to represent the blank customer properties
distil.trackEvent('EventName', 'Event Value', dataLayer.eventCustomProperties, {}, dataLayer.additionalProperties);

//Event info with additional custom properties, customer properties and additional behavioural properties
distil.trackEvent('EventName', 'Event Value', dataLayer.eventCustomProperties, dataLayer.customerProperties, dataLayer.additionalProperties);

 

 

Was this article helpful?

Comments

0 comments

Article is closed for comments.

Still have questions?

Contact us