Skip to content

Javascript Tracker

Peter Adams edited this page Sep 19, 2021 · 1 revision

Tracker is OWA's JavaScript tracking client. Tracker is responsible for tracking events that happen in the browser and reporting them back to an OWA server instance for analysis and reporting.

Adding Tracker to Your Web Page

This section discusses the code used to add the tracker to your web page. OWA will generate a customized version of this code for each site that you add to the site roster. See the ''Administration -> Site Roster'' page within OWA's management interface to get the tracking code for a particular web site and use that code as a starting place for further customizing how you want the tracker to behave.

The javascript code that is used to add OWA tracking to your web site comes in two flavors: ''traditional'' and ''async''. As of OWA v1.4.0 we recommend usng the ''async'' tracking tag, however both will continue to work. To add OWA tracking simple cut and past the tracking code into your web pages.

Traditional Tracker Code

<script type="text/javascript">
//<![CDATA[
var owa_baseUrl = "http://your.domain.com/path/to/owa/";
document.write(unescape("<script src='" + owa_baseUrl + "modules/base/js/owa.tracker-combined-min.js' type='text/javascript'> </script>"));
//]]>
</script>

<script type="text/javascript">
//<![CDATA[
try {
   OWA.setSetting('baseUrl', owa_baseUrl);
   OWATracker = new OWA.tracker();
   OWATracker.setSiteId('your_site_id');
   OWATracker.trackPageView();
   OWATracker.trackClicks();
   OWATracker.trackDomStream();
} catch(err) {}
//]]>
</script>

Lets consider each line one by one:

var owa_baseUrl = 'http://your.domain.com/path/to/owa/';

This global variable tells all OWA javascript objects (trackers, overlay's etc.) where the OWA server is located.

OWATracker = new OWA.tracker();

This create a new tracker object as a global javascript variable called OWATracker. You can change the name of this variable to whatever you want.

OWATracker.setSiteId('your_site_id');

Sets the Id of the site that you are tracking so that this ID will be logged as part of all events recorded by the Tracker. Site IDs are generated by the OWA admin interface whenever you add a new site to track.

OWATracker.trackPageView();

This line tells the tracker to track the page view and send the event to the server. If you want to pass custom event attributes (like page type, or title, etc.) be sure to set those before trackPageViewmethod is called or else they will not make it into the event before it is sent to the server.

Async Tracker Code

The async tracker code take advantage of modern browser's ability to download ad execute JavaScript without holding up the page from loading.

<script type="text/javascript">
//<![CDATA[
var owa_baseUrl = 'http://your.domain.com/path/to/owa/';
var owa_cmds = owa_cmds || [];
owa_cmds.push(['setSiteId', 'your_site_id']);
owa_cmds.push(['trackPageView']);
owa_cmds.push(['trackClicks']);
owa_cmds.push(['trackDomStream']);

(function() {
	var _owa = document.createElement('script'); _owa.type = 'text/javascript'; _owa.async = true;
	_owa.src = owa_baseUrl + 'modules/base/js/owa.tracker-combined-min.js';
	var _owa_s = document.getElementsByTagName('script')[0]; _owa_s.parentNode.insertBefore(_owa, _owa_s);
}());
//]]>
</script>

Lets consider each line one by one:

var owa_baseUrl = 'http://your.domain.com/path/to/owa/';

This global variable tells all OWA javascript objects (trackers, overlay's etc.) where the OWA server is located.

var owa_cmds = owa_cmds || [];

The owa_cmds is a global variable that houses the queue of commands that you want to execute when the tracker becomes available.

owa_cmds.push(['setSiteId', 'your_site_id']);

This line adds a command to execute the setSiteId method after the tracker is downloaded and becomes available. Commands take the from of a javascript array whose first value is the method that you wish to execute followed by values that will be passed to the method as arguments. In this case, we are going to pass the value ''your_site_id'' to the setSiteId method.

(function() {
	var _owa = document.createElement('script'); _owa.type = 'text/javascript'; _owa.async = true;
	_owa.src = owa_baseUrl + 'modules/base/js/owa.tracker-combined-min.js';
	var _owa_s = document.getElementsByTagName('script')[0]; _owa_s.parentNode.insertBefore(_owa, _owa_s);
}());

This is an anonymous function that will insert a <script> tag into your web page that will download the tracker library from the server.

Click Tracking

Tracker can be configured to track any clicks that occur on any DOM element of your web pages. This includes links, buttons, images, form elements as well as all HTML elements such as span, div, p. Tracker will report these click events back to the server as they happen via <img> tag requests.

trackClicks()

To tell the Tracker to track clicks just call the trackClicks() method on your Tracker object like so:

OWATracker.trackClicks();

DomStream Tracking

Tracker can be configured to record the mouse oriented DOM events (movement, click, focus, etc.) that a user generates while they interact with your web page. The Tracker will record this "Dom Stream" and periodically send it to the server as a single event.

NOTE: The Domstream module must be activated in your OWA instance to record and playback Dom Streams.

trackDomStream()

To track the Dom Stream of users call the trackDomStream() method on your Tracker object like so:

OWATracker.trackDomStream();

You can adjust the percentage of time that Domstreams are recorded by setting the logDomStreamPercentage option by calling the setOption() method on your Tracker object like so:

OWATracker.setOption('logDomStreamPercentage', 10)

The numeric value will be interpreted as a percentage.

Action Tracking

Often time you web site will contain specific "actions" that your users can perform that need to be tracked separately of page views. This could be the submission of a web form, or the click on a particular link or element on a web page.

trackAction()

It is possible to track an unlimited number of custom actions using the trackAction method. This method takes four parameters.

Parameters

Param Type Description
action_group string Required. This is the name by which you will later be able to "group" actions in your reporting (i.e. "Cooking").
action_name string Required. This is the name of the action. Unique names will count as unique actions (i.e. "Recipe Print").
action_label string Optional. This is an optional text label that can be used to further describe the action (i.e. "Best Chicken Parmesan Recipe").
numeric_value integer Optional. This is a number that you can store along with each event. This value will be summarized in reporting.

Example

OWATracker.trackAction('Cooking', 'Recipe Print',  'Best Chicken Parmesan Recipe', 10);

E-commerce Tracking

The tracker contains methods for tracking e-commerce transactions the products that are purchased as part of that transaction. See ecommerce tracking for more info on how these methods work.

These methods do not perform any calculations, such as quantity,revenue, or currency calculations. Keep the following in mind when using these methods:

  • You must make sure that the total amount of your transaction is equal to the sum of the implied value (unit price x quantity) of product line items that you associate with it using addTransactionLineItem().
  • Ensure that each product you add has its own unique name and SKU.
  • A refund can be represented by creating a new transaction with a with negative total and negative quantities in its associated line items.

addTransaction()

OWATracker.addTransaction( order_id, order_source, total, tax, shipping, gateway, city, state, country )

Creates an e-commerce transaction object with the values passed.

Parameters

Param Type Description
order_id string Required. The unique ID assigned to the transaction by your e-commerce shopping cart application.
order_source string Optional. The store name or partner channel associated with the transaction.
total string Required. The total amount of the transaction.
tax string Optional. The amount of tax associated with the transaction.
shipping string Optional. The cost of shipping associated with the transaction.
gateway string Optional. The name of the transaction gateway or shopping cart application associated with the transaction.
city string Optional. The city associated with the transaction.
state string Optional. The state associated with the transaction.
country string Optional. The country associated with the transaction.

addTransactionLineItem()

OWATracker.addTransactionLineItem( order_id, sku, product_name, category, unit_price, quantity )

Adds a product line item containing information about the product and the quantity that was purchased as part of the transaction. You can call this method repeatedly to add multiple unique product line items to the transaction, however only add a single line item for each unique product that is part of the transaction.

The AddTransaction method must be called prior to using this method.

Paramaters

Param Type Description
order_id string Required. The unique ID assigned to the transaction by your e-commerce shopping cart application. Should be the same as the value used in the addTransaction.
SKU string Optional. The SKU of the product associated with the line item.
product_name string Required. The name of the product associated with the line item.
category string Optional. The category of the product associated with the line item.
unit_price string Required. The unit price of the product associated with the line item.
quantity string Required. The quantity of the product purchased associated with the line item.

trackTransaction()

This method sends the e-commerce transaction and any associated product line items to the server.

OWATracker.trackTransaction();

Using Multiple Trackers on the Same Web Page

You can create and configure more than one tracker. To do so just store each tracker in a different global javascript variable like so:

OWATracker = new OWA.tracker();
OWATracker2 = new OWA.tracker();

Using the async code you simply have to refer to the variable names when adding methods to the command queue. For example:

owa_cmds.push(['trackPageView']); // refers to the default tracker object called OWATracker
owa_cmds.push(['OWATracker2.trackPageView']); // this will create the OWATracker2 object if it doesn't already exist and then call this trackpageView method.

Custom Event Tracking

You can use the Tracker to track custom event types that you define. Custom events should only be used when you need to track complex events and control the processing of that event on the server. If you only need ot track simple "actions" then use the Action Tracking methods instead.

The following code illustrates how to create a custom event, set an event type that your server will listen for, set an event property (name/value pair), and log it:

var myEvent = OWATracker.makeEvent();
myEvent.setEventType("someeventname");	
myEvent.set("somename", "somevalue");
OWATracker.trackEvent(myEvent)

This event will be sent to the server for processing. You can create an Event Handler to listen for this event and an entity if you want to log it to a new database table.

Cross Domain Tracking

Sometimes it is necessary to track the same visitor across two different web domains without that them appearing as a separate visitors on each of the domains. To accomplish this, you can tell OWA to share the contents of the visitor's OWA's cookies with the other web site that is also being tracked by OWA. There are three OWA tracker methods that enable you to do this.

shareStateByLink( url )

This method is used to pass a visitor's OWA state via a text link to another instance of OWA running on another web domain. The method takes the full URL of the link as an argument and is typically called as an "onclick" handler. For example:

<a href="/some_page.html" onclick="OWATracker.shareStateByLink(this.href); return false;">Test Link</a>

shareStateByPost( form )

This method is used to pass a visitor's OWA state to another web domain via a http POST operation such as a form submit. This method take the form object as an argument and is typically used as an "onsubmit" handler. For example:

<form action="http://www.someotherdomain.com/formHandler.php" 
     name="myform" method="post" onsubmit="OWATracker.shareStateByPost( this );">
. . .
</form>

checkForLinkedState

This method should be added to the OWA tracker that is running under the web domain you want to share the visitor's state with. This method will look for the shared state on the URL and then use store that shared state in cookies instead of creating new state for the visitor. This has the effect of making the visitor's session appear to be in progress" to the tracker which now use the shared visitor ID, session ID etc.

Here is an example of how to call this method.

<script type="text/javascript">
//<![CDATA[
var owa_baseUrl = 'http://your.domain.com/path/to/owa/';
var owa_cmds = owa_cmds || [];
owa_cmds.push(['setSiteId', 'your_site_id']);
owa_cmds.push(['checkForLinkedState']);
owa_cmds.push(['trackPageView']);
owa_cmds.push(['trackClicks']);
owa_cmds.push(['trackDomStream']);

(function() {
	var _owa = document.createElement('script'); _owa.type = 'text/javascript'; _owa.async = true;
	_owa.src = owa_baseUrl + 'modules/base/js/owa.tracker-combined-min.js';
	var _owa_s = document.getElementsByTagName('script')[0]; _owa_s.parentNode.insertBefore(_owa, _owa_s);
}());
//]]>
</script>

Cookie Domain and Sub Domain Tracking

When the tracker is included on a web page that is part of a sub domain (i.e. not 'www') it will automatically use the full sub domain for setting its cookies. You can alter that behavior and set an alternative higher level domain by calling the setCookieDomain method.

When tracking pages under a domain that begins with "www" (i.e. "www.yourdomain.com"), OWA will automatically strip the "www" and use a higher level domain for setting it's cookies (i.e. "yourdomain.com"). You can stop this from happening by calling setCookieDomain and passing the domain that you want to use.

setCookieDomain()

setCookieDomain( domain )

Alters the domain name used when setting cookies. A leading "." will be added to all domains.

Parameters

  • domain (string) - The full domain name to be used.

Custom Variables

setCustomVar()

setCustomVar( slot, name, value, scope )

Sets a Custom Variables that will be recorded with each tracking event. Variables can set for a single page or persisted and set on all requests made in the current and/or future visits.

Parameters

Param Type Description
slot integer Required. The variable slot to set. Currently OWA supports 1-5.
name string Required. The name portion of the variable.
value string Required. The value portion of the variable.
scope string Required. The scope of the variable. Allowed values include: page

Adding Search Engines

You can add to list of domains that the tracker will recognize as an organic search engine source of traffic. The addOrganicSearchEngine method take a domain name (e.g. search.foo.com) as well as the url parameter that the tracker should look at in order to retrieve the query terms used in the search.

owa_cmds.push(['addOrganicSearchEngine', 'somedomain.com', 'somequerystringparam']);

This configuration method should be called before all tracking methods.

Tracker Development

The tracker code is contained in the owa.tracker.js file. Tracker relies on some other javascript files and functions which are all concatenated and minimized into a single file called owa.tracker-combined-min.js during the OWA Building OWA.

Hooks

Developers can hook into the tracker using custom filter and action functions. A filter function should be used when you want to inspect and change a value (i.e. changing event properties). An action function should be used when you want to perform an action at a particular point in the tracker's execution (i.e. during initialization or after an event is logged, etc.)

Available Hooks

Filters

Name Description
tracker.log_event_properties The full set of event properties right before they are sent to OWA for logging.
tracker.default_options The tracker's default configuration options.

Actions

Name Description
tracker.init Fires once the tracker is loaded.

Registering a filter function

Registering a filter hook function requires three params:

Param Type Description
filter name string Required. This is the name of the filter hook that you want your function to run against.
callback function Required. This is the callback function to be run. The function can be anaanonymous function or a function/method signature. Either way, the callback must accept a single argument for the value to be filters and must return the value or else the filter chain will break.
priority integer Optional. This is an optional number used to set the order that the callback will run in case there are multiple filter callback registered for the same hook. A lower number denotes a higher priority. The default is 10.

Registering a hook function is similar to issuing a tracking command.

The following will register an anonymous filter function for the tracker.log_event_properties filter hook:

owa_cmds.push( ['OWA.addFilter', 'tracker.log_event_properties', function(value) { console.log('hello world'); return value;}, 10 ] );

Alternatively you could register an existing method or function:

function helloWorld( value ) {
    console.log('hello world'); 
    return value;
}

owa_cmds.push( ['OWA.addFilter', 'tracker.log_event_properties', helloWorld, 10 ] );