Tracking Script API

On this page you find information about the Keytiles Tracking Script API - so you can gain full control over when and how to generate a hit Keytiles will track.

Content of this page

Object hierarchy and bootstrapping

We have three important objects (from your perspective) in Keytiles tracking script

  • KeytilesTracking
    This is a static utility class - the backbone of the tracking. The class is responsible for wiring everything together and provide the bootstrapping once the tracking script is loaded
  • KeytilesTrackingApi
    This is what you will interact with when want to send in manually created hits into Keytiles. The object has both static and instance methods. And there is one object instance created / each Containers you use in Keytiles to track your data.
  • keytilesTrackingConfig
    This is a window level (global) variable which KeytilesTracking recognizes and act accordingly - you need this to get into the cockpit with your JavaScript codes.

When the tracking script is loaded the KeytilesTracking object will start the init sequence.

Please note that you have loaded the tracking script in the scope of a Container already! As you can see there is a containerId already in the below url:

https://scripts.keytiles.com/tracking/<your-container-id>/stat.js

which will act as your "default" container.

You have the possibility to add more "additional" containerIds in the keytilesTrackingConfig object (but this is a really advanced topic if you use multi containers and not just one).

During the init sequence the KeytilesTracking object will

  • Create an instance of KeytilesTrackingApi for all Containers.
    If you configured you will receive a call on your callback (see the below example!) method / each. By using the appropriate instance you send hits to the appropriate Container of yours.
  • Trigger mechanisms like browser fingerprinting, browser window tab tracking, etc etc.
    This is not really your concern however it is good to know for you that these take time to complete! It is normally a few hundred millisecs but sometimes more. The point is: until these mechanisms are not finished the tracking script will not send out hits at all but queue them. And they will be sent out from this queue once this part of the init is done.

Getting a reference to the tracking API object

Normally Keytiles tracking script is loaded asynchronously and before this happens you can not interact with the API of course. The tracking offers you notification mechanism via callback methods to let you know when tracking becomes available.

For that you will need to use the keytilesTrackingConfig object to get into control.

Via the keytilesTrackingConfig object

The keytilesTrackingConfig variable is a Window level (global) variable and defines a pretty straightforward Object. With this object you can:

  • Turn on different level console logs - useful for debugging purposes
  • Disable auto-tracking which normally happens after the script is loaded (so on page load basically)
  • Provide callback function to the tracking API - which is invoked as soon as the tracker belongs to a Container becomes available.

Check this example - you will understand it quickly!

<script type="text/javascript">

	/**
	 * Your callback method
	 * This will be invoked for every containers (typically you just have one, but if you
	 * defined additional ones in keytilesTrackingConfig.additionalContainerIds then you will have more)
	 * 
	 * @param {KeytilesTrackingApi} keytilesTrackerApiObject- the Keytiles API object instance
	 */
	function onKeytilesTrackerAvailable(keytilesTrackerApiObject) {
		// you can work with the keytilesTrackerApiObject here
		console.log("tracking became available for containerId: "+keytilesTrackerApiObject.containerId;
	}

    /**
     * Optional config object on window level - the tracking script will recognize it
     */
    var keytilesTrackingConfig = {
        // boolean - wether to auto-fire the pageview track mechanism right after script is ready or not
        autoTrackingEnabled: false,
        // String array - if you have multiple containers here you can define the ids in a String array
        // of the additional containerIds
        additionalContainerIds: [],
        // int - for debugging, values can be
        // 0 - none, 1 - error, 2 - warn, 3 - info, 4 - debug
        consoleLogLevel: 0,
        // we setup our callback function which will be called as soon as tracking script was initialized
        // function reference - to callback, the API object is passed as a parameter
        onTrackerAvailableCallbackFunc: onKeytilesTrackerAvailable,
        // boolean option, default is FALSE
        // By default Keytiles is using the commonly used technique to send hits to the servers - by
		// loading an 1x1 invisible <img> into the page and hit attributes are sent in the request parameters
        // But if you set this flag to TRUE then Keytiles will use XmlHttpRequests (ajax) instead of 
		// the <img> load trick sent to our JSON api endpoint
        useJSONEndpoint: true
    };

	/**
	 * and now let's pull in the tracking script!
	 */
	(function () {
	  var kt = document.createElement('script');
	  kt.type = 'text/javascript';
	  kt.async = true;
	  kt.src = document.location.protocol+'//scripts.keytiles.com/tracking/<your-container-id>/stat.js';
	  var s = document.getElementsByTagName('script')[0];
	  s.parentNode.insertBefore(kt, s);
	})();
	
</script>

Statically - through the KeytilesTracking object

You can get the KeytilesTrackingApi object instance belongs to a specific Container any time using the KeytilesTracker.getTrackingApiInstance() method

KeytilesTrackingApi - reference

This is the most important object in Keytiles tracking for you - as you will interact with Keytiles hit sending mechanism through this object.

Static vs instance methods/variables

This object has both static and instance methods and variables. The ones which relate to a concrete Container are instance methods/variables. While the others which are kind of "global" are static.

Static methods and variables

KeytilesTrackingApi.ACTION_TYPE_PAGEVIEW

KeytilesTrackingApi.ACTION_TYPE_PAGEVIEW = "pageview";

KeytilesTrackingApi.EVENT_TYPE_xxx constants

When you invoke the .trackEvent() method you need to name the eventType you want to send. That can be basically any kind of string but we have several predefined string to be used here.


KeytilesTrackingApi.EVENTTYPE_PAGEVIEW = "pageview";
KeytilesTrackingApi.EVENTTYPE_VIEW = "view";
KeytilesTrackingApi.EVENTTYPE_DOWNLOAD = "download";
KeytilesTrackingApi.EVENTTYPE_UPLOAD = "upload";
KeytilesTrackingApi.EVENTTYPE_LOGIN = "login";
KeytilesTrackingApi.EVENTTYPE_LOGOUT = "logout";
KeytilesTrackingApi.EVENTTYPE_PING = "ping";
KeytilesTrackingApi.EVENTTYPE_SCROLLED_TO = "scrolledTo";
KeytilesTrackingApi.EVENTTYPE_SUBMITTED = "submitted"; // e.g. a form

KeytilesTrackingApi.isTrackingReady()

/**
 * @return {boolean} TRUE if yes, FALSE if not yet
 */
KeytilesTrackingApi.isTrackingReady: function() {}

Checks if Keytiles tracking init completed or not - including all mechanisms.

KeytilesTrackingApi.isTrackingEnabled()

/**
 * @return {boolean} TRUE if yes, FALSE if not
 */
KeytilesTrackingApi.isTrackingEnabled: function() {}

Tells - based on visitor consents - if it is allowed for Keytiles to track actions on the page or not.

In case the answer is FALSE then Keytiles will not send anything up to Keytiles servers from this device. Hence it is pointless to run / waste time on any custom mechanisms you potentially built around Keytiles.

KeytilesTrackingApi.buildHitOptions()

/**
 * @return {Object} containing prepared hit attributes
 */
buildHitOptions = function() {}

Building up an Object with default attributes/options of the hit and hit sending - which you will then pass to .trackEvent() calls. 

Of course you can change / customize the values if you want before you do the call!

Please note: if you are using meta tags in your page they influence these default values heavily!

The object has the following entries (and more can be there - you can notice) after the method call:

  • tileIdtileTypetileGroupPath, tileLanguagetileTitle and tileUrl
    To understand these better please read Hit attributes article, and check the Attribute reference section there!
  • userAgentType
    The tracking script detects if this is a mobile or a desktop web browser and this is indicated in this field. Value will be one of these constants:
    • KeytilesTracking.USER_AGENT_TYPE_DESKTOP
    • KeytilesTracking.USER_AGENT_TYPE_MOBILE
  • value
    This is an >0 integer: how many hits the content received. This is typically - so by default is: 1. But if this hit represents more than 1 hits then you can increase this value accordingly.

The .trackEvent() method accepts further entries as part of the options you might be interested in! 

KeytilesTrackingApi.deleteAllStoredInformation()

/**
 * @see #KeytilesTrackingApi.setVisitorTrackingConsent()
 */
KeytilesTrackingApi.deleteAllStoredInformation = function() {}

Immediately removes all cookies (including user consents storage ones!!) / local storage entries Keytiles tracking script ever created or using.

Use this method only if you plan not to include the Keytiles tracking script any longer and you need a permanent and full flush!

If this is not the case, you still want to include the Keytiles tracking but just tell him "hey do not store any info any longer on the visitors machine!" - you should use the KeytilesTrackingApi.setVisitorTrackingConsent() method instead!

KeytilesTrackingApi.setVisitorTrackingConsent()

/**
 * @param {boolean} userConsentGranted TRUE if visitor agrees to track activities - FALSE if he does not
 */
KeytilesTrackingApi.setVisitorTrackingConsent = function(userConsentGranted) {}

To easily mark "Visitor disagrees" fact for entire Keytiles tracking.

If user disagrees then this method will immediately invoke KeytilesTrackingApi.deleteAllStoredInformation() removing all locally stored info and KeytilesTracking.COOKIENAME_USER_EXCLUDE_DEVICE cookie is placed to store this fact.

From this moment Keytiles tracking will be completely back off on this device and will not send any actions until consent is granted again.

KeytilesTrackingApi.getVisitorTrackingConsent()

/**
 * @return TRUE if user consent is positive - FALSE if we do not have the user consent
 */
KeytilesTrackingApi.getVisitorTrackingConsent = function() {}

You can query the current state of the visitor consent - see KeytilesTrackingApi.setVisitorTrackingConsent()

KeytilesTrackingApi.setVisitorDeviceIdentificationConsent()

/**
 * @param {boolean} userConsentGranted TRUE if visitor agrees to track activities - FALSE if he does not
 */
KeytilesTrackingApi.setVisitorDeviceIdentificationConsent = function(userConsentGranted) {}

This consent is not that strong as KeytilesTrackingApi.setVisitorTrackingConsent() - it is "just about" placing a unique ID on this device.

If visitor disagrees here then cookie KeytilesTracking.COOKIENAME_UNIQUE_WEBCLIENT_ID is removed and fact visitor disagrees is marked in KeytilesTracking.COOKIENAME_USER_DEVICEID_CONSENT_DENIED cookie.

KeytilesTrackingApi.getVisitorDeviceIdentificationConsent()

/**
 * @return TRUE if user consent is positive - FALSE if we do not have the user consent
 */
KeytilesTrackingApi.getVisitorDeviceIdentificationConsent = function() {}

You can query the current state of the visitor consent - see KeytilesTrackingApi.setVisitorDeviceIdentificationConsent()

Instance methods and variables

.containerId

This is a String variable. The id of the container this tracking object will send hits to.

.currentTileId

This is a String variable. See .setCurrentTile() method for more details!

.setCurrentTile()

/**
 * @param {String} tileId the id of the tile you want to set as "current"
 */
setCurrentTile: function(tileId) {}

Brings the tracking script to the state that it stores the given tile as 'current tile'.

So all subsequent .trackPageview() or .trackEvent() calls will consider this tile as caller / origin / referrer tile - whenever the tileId you give to trackEvent() / trackPageview() methods is not equal to this stored one

.trackPageview()

This method is DEPRECATED! Please use .trackEvent() method instead!

/**
 * @param {Object} options - see description at #trackEvent() method!
 */
trackPageview: function(options) {}

Just a wrapper around the .trackEvent() method - firing that with actionType = ACTION_TYPE_PAGEVIEW

.trackAction() 

This method is DEPRECATED! Please use .trackEvent() method instead!

.trackEvent() 

/**
 * @param {String} eventType with this action type - see KeytilesTrackingApi.EVENT_TYPE_xxx constants!
 * @param {Object} options using properties collected and stored in this object - see #KeytilesTrackingApi.buildHitOptions() static method
 */
trackEvent: function (eventType, options) {}

Assembles and fires a hit to Keytiles servers.

The eventType parameter can be basically any kind of string naming the event. For comfort there are several pre-defined strings for even types - see KeytilesTrackingApi.EVENTTYPE_xxx constants!

The options parameter is an object. It is recommended to assemble a default object using the KeytilesTrackingApi.buildHitOptions() method. Which you can customize before passing in to this method.

But there are further optional attributes you can add to this object before passing it over! They are the following:

  • referrerTileId
    The id of the tile the visitor came from to this tile which is in the scope of the hit you are going to send now. Presence of this attribute helps Keytiles a lot to build visitor flow tracking correctly.
    note: There is a mechanism in place which goes with a "best effort" approach to provide this value if possible and this is related in one hand to the .setCurrentTile() method (very useful if you are building advanced tracking for "one-pager" pages) and in other hand to the kt_tileIdByUrl map stored in Local Storage of the browser. So you don't need to use this typically but you can come up with very exact mechanism if you wish and can.
  • resultCallbackFunc
    You can provide a function reference here which will be invoked once the hit was sent to the Keytiles servers.
    The method you give here will receive parameters, so you should make the signature accordingly.
    /**
     * @param {boolean} wasSuccess - was sending successful?
     * @param {string} containerId - the target containerId the hit was sent to
     * @param {object} hitOptions - the hit attributes object
     */
    function onKeytilesHitSent(wasSuccess, containerId, hitOptions) {}

     

.buildHitOptions()

Is a comfort wrapper for KeytilesTrackingApi.buildHitOptions() static method on instance level.

.isTrackingReady()

Is a comfort wrapper for KeytilesTrackingApi.isTrackingReady() static method on instance level.

.isTrackingEnabled()

Is a comfort wrapper for KeytilesTrackingApi.isTrackingEnabled() static method on instance level.

KeytilesTracking - reference

This is a static utility class as we described above so it has just static functions and constants.

Constants

KeytilesTracking.VERSION

String, the version of the tracking script in format major.minor.patch

Tracking script follows semantical versioning policy.

KeytilesTracking.COOKIENAME_USER_EXCLUDE_DEVICE

KeytilesTracking.COOKIENAME_USER_EXCLUDE_DEVICE = "kt_excludeDevice";

This holds the name of the cookie we store the fact visitor disagrees with any form of the tracking. It is a boolean cookie and only present if value is TRUE - so if visitor said "no I disagree completely"

You should not handle this cookie directly!

KeytilesTracking.COOKIENAME_USER_DEVICEID_CONSENT_DENIED

KeytilesTracking.COOKIENAME_USER_DEVICEID_CONSENT_DENIED = "kt_deviceIdConsentDenied";

This holds the name of the cookie we store the fact visitor disagrees with using of the KeytilesTracking.COOKIENAME_UNIQUE_WEBCLIENT_ID cookie to store a randomly generated unique ID for this device. It is a boolean cookie and only present if value is TRUE - so if visitor said "no I disagree"

Please note that this disagreement still does not mean tracking is disabled! Keytiles will still send actions but without any device ID which would mean these actions will remain isolated - there is no way to build Visit Sessions out of these user activities. It is also not possible in this case to recognize "returning visitors" anymore.

KeytilesTracking.COOKIENAME_UNIQUE_WEBCLIENT_ID

KeytilesTracking.COOKIENAME_UNIQUE_WEBCLIENT_ID = "kt_uniqueWebClientId";

This holds the name of the cookie we store the randomly generated unique ID to recognize this device. It is only present if visitor agrees to this activity (see KeytilesTracking.COOKIENAME_USER_DEVICEID_CONSENT_DENIED cookie).

The value is a randomly generated UUID style string we use to uniquely identify the web browser (of the visitor) now and in the future.
As a) this is a random string it does not contain any sensitive information and b) this is on a per Container level (not shared among multi containers)
means it is not suitable to trace back the person behind it not even on guessing level, so this Cookie is safe from GDPR perspective as design does not allow cross-data mining.

You should not handle this cookie directly!

KeytilesTracking.COOKIE_NAMES

Array, the list of all Cookie names used by the tracking (and we listed above)

KeytilesTracking.STORAGE

Array, the list of all variables stored in Local Storage

KeytilesTracking.USER_AGENT_TYPE_DESKTOP

KeytilesTracking.USER_AGENT_TYPE_DESKTOP = 'browser-desktop';

This is a Desktop web browser - See the userAgentType key in the object returned by KeytilesTrackingApi.buildHitOptions()!

KeytilesTracking.USER_AGENT_TYPE_MOBILE

KeytilesTracking.USER_AGENT_TYPE_MOBILE = 'browser-mobile';

This is a Mobile web browser - See the userAgentType key in the object returned by KeytilesTrackingApi.buildHitOptions()!

Static methods and variables

KeytilesTracking.defaultContainerId

String, the containerId where the tracking script was loaded from as scope. See above!

KeytilesTracking.browserTabId

String, the generated ID of the current Browser Tab.

This field is only available after init sequence is completed - see KeytilesTrackingApi.isTrackingReady()

KeytilesTracking.isNewTab

Boolean, tells if the Browser Tab is new (so was just opened) or not

This field is only available after init sequence is completed - see KeytilesTrackingApi.isTrackingReady()

KeytilesTracking.uniqueWebClientId

String, the unique ID of this web browser. This is just available if Cookies are enabled - as value comes from the kt_uniqueWebClientId cookie

This field is only available after init sequence is completed - see KeytilesTrackingApi.isTrackingReady()

KeytilesTracking.pseudoUniqueWebClientId

String, result of the browser fingerprint generation.

This field is only available after init sequence is completed - see KeytilesTrackingApi.isTrackingReady()

KeytilesTracking.getAllTrackingApiInstances()

/**
 * @return {[{KeytilesTrackingApi}]}
 */
getAllTrackingApiInstances: function() {}

Returns all known KeytilesTrackingApi object instances.

Typically this will return just one element - except if you go with multi-container approach (which is a pretty advanced technique anyways)

KeytilesTracking.getTrackingApiInstance()

/**
 * @param {string} containerId the id of the container
 * @return {KeytilesTrackingApi}
 */
getTrackingApiInstance: function(containerId) {}

Returns the KeytilesTrackingApi object instance which belongs to the given Container - or NULL if there is no API object for that Container