Web SDK Public API Reference

The Tealeaf Web SDK supports the public interfaces that are listed here.

In the development builds of the library, several APIs throw exceptions and log the exception to the console when the library is not initiated for API calls that depend on the library. In production builds of the library, the API call fails silently if the library was not initialized.
The following APIs throw this exception in development builds.

  • getSessionData
  • logCustomEvent
  • logExceptionEvent
  • logScreenviewLoad
  • logScreenviewUnload
  • logScreenCapture

getDefaultConfig

The getDefaultConfig API returns the base default configuration object. You can use this returned object as a starting point to configure the Web SDK.

/**
  * Returns the base default global configuration object.
  * @name getDefaultConfig
  * @memberOf TLT
  * @function
  * @returns {Object} The base default global configuration object.
  */
"getDefaultConfig"

Example

const myConfig = TLT.getDefaultConfig()

In the example provided, the getDefaultConfig function is called, and the return value is assigned to the variable myConfig.

initLib

The initLib API initializes the Tealeaf system with the provided configuration information. You can use this API to start and run Tealeaf on your web application quickly.

The API sets up various modules, hooks up web events, and includes additional libraries needed for Tealeaf functionality. It includes the following additional javascript libraries needed as inline in your application.
- pako
- HammerJS 1.3
- Tealeaf gesture module
- construct-style-sheets-polyfill 3.1.0 when used on a Safari browser to help with dynamic styles capture
- Tealeaf Ajax listener
- helper to restart Tealeaf for a single-page application

The function takes the following two parameters:

  • appKey: The application key from the SaaS organization.
  • postUrl: The collector URL to which the data will be posted.
/**
  * Initializes the system. The default configuration information is passed to the
  * config service to manage it. All modules are started and web events
  * are hooked up.
  * @param {String} [appKey] The application key from SaaS organization.
  * @param {String} [postUrl] The collector url to post data.
  * @returns {void}
  */
initLib: function (appKey, postUrl)

Example

window.TLT && window.TLT.initLib("appkeyvalue","<https://brilliantcollector">);

In the example provided, the initLib function is called on the window.TLT object. It checks if the TLT object exists and then initializes Tealeaf with the provided application key and collector URL.

initLibAdv

The initLibAdv API initializes the Tealeaf system with the provided configuration information. You can use this API to start and run Tealeaf on your web application quickly.

The API sets up various modules, hooks up web events, and allows for the inclusion of additional libraries that are needed for Tealeaf functionality. It includes the following additional javascript libraries needed as inline in your application.
- pako
- HammerJS 1.3
- Tealeaf gesture module
- construct-style-sheets-polyfill 3.1.0 when used on a Safari browser to help with dynamic styles capture
- Tealeaf Ajax listener
- helper to restart Tealeaf for a single-page application

The function takes several parameters:

  • appKey: The application key from the SaaS organization.
  • postUrl: The collector URL to which the data will be posted.
  • newConfig: A configuration object to use without the application key and post URL.
  • addPako: A boolean indicating whether to add the pako library.
  • addHammer: A boolean indicating whether to add the HammerJS 1.3 library.
  • addSafariPolyFill: A boolean indicating whether to add the construct-style-sheets-polyfill 3.1.0 library for Safari browsers to help capture dynamic styles.
  • addAjaxListener: A boolean indicating whether to add the Tealeaf Ajax listener.
  • addRestartTLTforSPA: A boolean indicating whether to add the helper for restarting Tealeaf for single-page applications.
/**
  * Initializes the system based on configuration information is passed to the
  * config service to manage it. All modules are started and web events
  * are hooked up. There are also options to add extra libaries needed for Tealeaf.
  * 
  * @param {String} [appKey] The application key from SaaS organization.
  * @param {String} [postUrl] The collector url to post data.
  * @param {Object} [newConfig] Configuration object to use without application key and post url.
  * @param {Boolean} [addPako] Whether to add pako.
  * @param {Boolean} [addHammer] Whether to add HammerJS.
  * @param {Boolean} [addSafariPolyFill] Whether to add construct-style-sheets-polyfill 3.1.0 to Safari browser to help with dynamic styles.
  * @param {Boolean} [addAjaxListener] Whether to add ajax listener.
  * @param {Boolean} [addRestartTLTforSPA] Whether to add Restart TLT for SPA helper.
  * @returns {Object} Configuration object used.
  */
initLibAdv: function (appKey, postUrl, newConfig, addPako, addHammer, addSafariPolyFill, addAjaxListener, addRestartTLTforSPA)

Example

const myConfig = TLT.getDefaultConfig()  
myConfig.core.buildNote = 'My custom config'  
TLT.initLibAdv('appkeyvalue','<https://brilliantcollector'>, myConfig, true, false, true, true, true)

In the example provided, getDefaultConfig is called to retrieve the base default global configuration object, which is assigned to myConfig. Then, the initLibAdv API is called with the various parameters to initialize Tealeaf with the specified configuration and include additional libraries.

TLT.getLibraryVersion()

TLT.getLibraryVersion() returns the version number of the Web SDK. It is recommended to use the latest version.

Example

version = TLT.getLibraryVersion();

TLT.init(object configObject, /optional/ function callbackFunction)

This API initializes the Tealeaf Web SDK with the specified configuration object. init execution occurs after the Document Object Model is loaded. The init call is asynchronous in nature, as the library only initializes after the Document Object Model is loaded. The calling code can choose to provide a callback function as a second parameter to this API. The library will invoke the callback function after it initializes.

  • The call to init can be included as part of the static JavaScript resource for static deployments.
  • For dynamic deployments, the call to init can be made from within the customer application.

Example

function initializeTealeaf(configObject) {
    if (TLT && !TLT.isInitialized()) {
        TLT.init(configObject);
    }
}
// Define a callback function to handle post-initialization tasks.
function tltPostInitCallback(state) {
    if (state === "initialized") {
        // Perform post initialization tasks
        ...
    } else {
        console.error("TLT not initialized - ", state);
    }
}

function initializeTealeaf(configObject) {
    if (TLT && !TLT.isInitialized()) {
        // Initialize Web SDK and specify the callback function to be invoked after initialization.
        TLT.init(config, tltPostInitCallback);
    }
}

TLT.IsInitialized()

This API returns true if the Web SDK is initialized. Otherwise, it returns false.

Example

function logToTealeaf(msg) {
	if (TLT && TLT.isInitialized()) {
		TLT.logCustomEvent("customMsg", msg);
	}
	/* Else take some other action such as queuing the message for future after Tealeaf is initialized */
}

TLT.rebind(/optional/ DOMElement root)

Rebind causes the Tealeaf Web SDK to reprocess its event listeners. The application can use this API to notify the Tealeaf Web SDK after the application made a dynamic update that added new user input elements to the Document Object Model.

The application can specify an optional root element from which the reprocessing occurs. If not specified, the reprocessing occurs from the document element. In a large and complex Document Object Model, specifying the exact subset that was updated with new user input elements improves efficiency.

Example

function callrebind() {

  TLT.rebind();

}

TLT.flushAll(void)

This API causes the buffered data that is gathered by the Tealeaf Web SDK to be flushed to its configured endpoint URL.

Typically, flush is used in combination with the setAutoFlush API call to gain precise control over network usage behavior in highly tuned mobile apps.

Example

function callflushAll() {

  TLT.flushAll();
}

This API is used to enable or disable the automatic flushing behavior of the library. Automatic flushing is enabled by default and is controlled by the configurable queue length.

To disable automatic flushing:

TLT.setAutoFlush(false)

To enable automatic flushing:

TLT.setAutoFlush(true)

📘

Note:

When automatic flushing is disabled, it is the application's responsibility to ensure the data that is buffered by the library is flushed out at appropriate intervals by starting the flushAll() API.

TLT.processDOMEvent(DOMEvent event)

This API is used to explicitly inform the Tealeaf Web SDK of any Document Object Model event that the library was configured to listen to but is actively blocked by the application from bubbling.

In this case, the application or site can make an explicit API call. The argument is the DOMEvent object that is passed by the browser to the event handler.

It also applies to similar actions that prevent the Web SDK from automatically processing the event.

Example

$(document).ready(function(){
   $( ".disable" ).click(function( event ) {  
     event.preventDefault();
     event.stopPropagation();

     // Notify Tealeaf
     if (TLT && TLT.processDOMEvent) {
            TLT.processDOMEvent(event);
     }

     $( "<div>" ).append( "default " + event.type + " prevented" ).
     appendTo( "#log" );
     });
   });

TLT.logCustomEvent(DOMString name, object customMsgObj)

The application can use this API to log a custom message into the Web SDK's message stream.

The customMsgObj parameter to this function specifies the object to be serialized and passed as a custom message.

The custom message can be processed on the back-end for step-based eventing and reporting.

Note: There is a max. limit of 300 custom messages per page.

Example

if (TLT.isInitialized()) {
    TLT.logCustomEvent("apiMetrics", {
        url: "/v1.0/getAccountInfo",
        status: 200,
        retries: 0,
        errorCode: 0
    });
}

TLT.logExceptionEvent(DOMString msg, /optional/ DOMString url, /optional/ long line)

The application can use this API to log an error or exception message into the Tealeaf Web SDK 's message stream.

Specifying the URL and line number of the error message is optional.

📘

Note:

There is a max. limit of 400 exception messages per page.

function calllogExceptionEventh() {

  TLT.logExceptionEvent("This is to test the TLT.logExceptionEvent()","/
  APITesting/testRebind.html",101);
}

To register error event handlers, add

"{ name: "error", target: window }"

to the replay module. Exception reporting follows this behavior:

  • If the error event is not registered, exception reports are not sent.
  • If the event is registered,
  • but no errors are thrown, the exception report is not sent.
  • errors are thrown, then log the first occurrence of the exception inline. This is useful for analysis since the exact occurrence of the exception within the context of the user interaction can be seen.

Example

This is an example of an Exception (Type 6) message. This example exception indicates an attempt to read a property named 'foo' of a variable or value which is undefined.

{
	"type": 6,
	"offset": 7279,
	"screenviewOffset": 7264,
	"count": 7,
	"fromWeb": true,
	"exception": {
		"description": "Uncaught TypeError: Cannot read property 'foo' of undefined",
		"url": "http://uictest.com/h4/index.html",
		"line": 93
	}
}

Any subsequent occurrence of the same exception is not be logged and only counted. If the repeat value is > 1, log the exception message again on screenview unload and include the repeat count.

{
	"type": 6,
	"offset": 19155,
	"screenviewOffset": 19039,
	"count": 15,
	"fromWeb": true,
	"exception": {
		"description": "Uncaught TypeError: Cannot read property 'foo' of undefined",
		"url": "http://uictest.com/h4/index.html",
		"line": 93,
		"repeats": 4
	}
}

TLT.logScreenviewLoad(DOMString screenviewName, /optional/ DOMString referrerName, /optional/ DOMElement root) and TLT.logScreenviewUnload(DOMString screenviewName)

Applications can use the Web SDK API to log a screen view load message into the Tealeaf Web SDK's message stream.

The Web SDK tracks URL path and URL hash changes and automatically logs Screenview messages. The application can choose to disable the automatic Screenview logging and log the messages by using the TLT.logScreenviewLoad API call. It is a recommended practice to use TLT.logScreenviewLoad and TLT.logScreenviewUnload to capture the screenviews for use with Replay and analytics.

As an example, a typical checkout flow would have a payment screen where the visitor can enter their payment information. When the payment screen is displayed, the application can log the screenview LOAD message using the following snippet.

TLT.logScreenviewLoad("payment");

When the visitor exits the payment screen, the application can log the screenview UNLOAD message using the following snippet.

TLT.logScreenviewUnload("payment");

Note: The load and unload API call requires that the screenview name is the same for both calls.

You can use the referrerName parameter to log nested screenviews. For example, if the payment screen has a nested screen for credit card payments and another screen for direct payment from the bank, you can subcategorize the screenviews into creditcard and directpayment.

The following example shows how you can log the nested screenview for a payment screen that has two nested screenviews to accept credit card payments and direct payments.

TLT.logScreenviewLoad("payment");
TLT.logScreenviewLoad("creditcard", "payment");

If the user switches from entering a credit card payment to entering direct payment information, the following snippet is used to stop logging the credit card screenview and log the screenview for the direct payment.

TLT.logScreenviewUnload("creditcard");
TLT.logScreenviewLoad("directpayment", "payment");

As the user exits the payment section, the application uses the following snippet to end the screen logging.

TLT.logScreenviewUnload("directpayment");
TLT.logScreenviewUnload("payment");

TLT.getSessionData()

This API returns a Tealeaf session data object. The Tealeaf session ID information is included in this data.

An optional flag indicates if the session ID must be derived by hashing the session value in the object.

An example of a returned value follows.

{
    tltSCN: "PHPSESSID",
    tltSCV: "joese2pun5nus50p45j38hrak5",
    tltSCVNeedsHashing: true                // Optional
}

To enable this API, the library must be configured with the appropriate configuration settings. These settings inform the library from where the session ID information is to be derived.

If the API is not enabled in the configuration or the specified data cannot be read, then null is returned.

Example

function getSessionData() {

  var _sessionData = TLT.getSessionData();
  var sessionId = _sessionData.tltSCN;
  var sessionVal = _sessionData.tltSCV;

  verifySessionData(sessionId, sessionVal)

}

TLT.registerBridgeCallbacks

This API can be used to register callback functions invoked by the Web SDK in specific instances.

🚧

Warning:

This is an advanced API, which can result in incorrect operation or loss of data if misused. This API should not be used in a hybrid application as the Tealeaf native logging frameworks register and use the appropriate bridge callbacks.
Currently, three callback types are supported: messageRedirect, screenCapture, and addRequestHeaders.

Example to register a callback

TLT.registerBridgeCallbacks([
     {enabled: true,
     cbType: 'screenCapture',
     cbFunction: function (){
       tlBridge.screenCapture();
     }
   },{
     enabled: true,
     order: 1,
     cbType: 'messageRedirect',
     cbFunction: function (msgStr, msg){
       tlBridge.addMessage(msg);
     }
   }
]);

When you register a messageRedirect callback function an optional "order" property can be specified. This property specifies the numerical order that multiple messageRedirect callback functions are invoked.

messageRedirect

This callback can be registered to redirect and intercept messages from the Web SDK. When this callback is registered, the Web SDK invokes the callback function for each message before you add it to the queue. The callback function is passed two parameters: the serialized JSON message and the same message as a JavaScript object.

The callback function can consume the message entirely and return null or undefined. In this case, the Web SDK discards the message.

The callback function can also modify the JavaScript object or return it unchanged. In this case, the Web SDK queues the returned object in its internal queue.

This API must not be used in a hybrid application as the Tealeaf native logging frameworks registers and uses this bridge callback.

Example of messageRedirectFunc

function messageRedirectFunc(msgStr, msg) {
    // Modify the mousedown type to a click
    if (msg.type === 4 && msg.event.type === "mousedown") {
        msg.event.type = "click";
    }
    return msg;
}

screenCapture

This callback function can be registered to enable a JavaScript API (see logScreenCapture) to allow a screen capture to be taken. The Web SDK starts the callback function when the logScreenCapture API is started.
This API must not be used in a hybrid application as the Tealeaf native logging frameworks registers and uses this bridge callback.

Example of screenCapture

function register_ScreenShot_Enable_CallBack() { 
TLT.registerBridgeCallbacks([
    {
        enabled: true,
        cbType: "screenCapture",
        cbFunction: myCbFunction
    }
]);
}

addRequestHeaders

This callback function can be registered to enable a third-party JavaScript to return custom HTTP headers that need to be set on the Web SDK POST request.

Example of addReqHeadersFunc

count = 1;
function addReqHeadersFunc() {
    var headers = [
        {
            name: "X-Counter",
            value: count
        }
    ];
    if (count === 1) {
        // Add a recurring header the 1st time.
        headers.push({
            name: "X-Custom-Id,
            value: customId,
            recurring: true
        });
    }
    count++;
    return headers;
}

TLT.logDOMCapture(/optional/ DOMElement root, /optional/ object configOptions)

Use this API for the Web SDK to log a DOM Capture message. If the root element is not specified, the DOM Capture is performed taking the document as the root.

The supported options for this API are:

  • captureFrames - Whether to capture frames or iframes. Values are true or false.
  • removeScript - Whether to remove script tags from the capture.
    The API returns a string that serves as the unique id associated with this DOM Capture message. If the DOM Capture feature is disabled or the capture could not be performed for any reason, the API returns null.

This example shows how to capture anything within the document body and to remove scripts:

// In the following example, the root parameter is the HTML body element. The capture will not
// contain anything outside the document body and will also remove any script tags occurring
// within the body element.
if (TLT && TLT.isInitialized()) {
    captureId = TLT.logDOMCapture(document.body, { removeScript: true });
}

This example shows how to capture anything within the document body, any iframes, and to remove scripts:

// In the following example, the root parameter is left as null which will cause the API to use
// the document as the default root. The capture will also include any iframes that are part of the
// document and do not violate the same-origin policy of the browser. The capture will remove
// any script tags occurring within the document.
if (TLT && TLT.isInitialized()) {
    captureId = TLT.logDOMCapture(null, { captureFrames: true, removeScript: true });
}

TLT.logFormCompletion(/boolean/ submitted, /[OPTIONAL] boolean/ valid)

Use this API for cxOverstat to produce the Form Completion report.

This API creates and adds a form completion message. Form completion indicates whether the user submitted a form (or a form equivalent) and whether the form was validated. The Web SDK should be able to post these types of messages for pages that have forms on them - they will indicate whether the user has submitted a form or not and optionally whether the form was valid or not.

The API accepts two parameters:

  • submitted: Boolean flag indicates whether the form (or form equivalent) was submitted (true) or not (false)

  • valid: Optional boolean flag indicates whether any validation was performed on the form input and if the validation check passed (true) or failed (false)
    Note: For a standard HTML form element, the submission is when the submit event is triggered. A submission is defined as per the business logic for applications that use AJAX.

    Example Form Completion JSON message

{
   type: 15,
   formCompletion: {
     submitted: true/false
     valid: true/false/null
   }
}

📘

Note:

This feature requires {name:"submit", recurseFrames: true } configuration setting for cxOverstat.

Example Default Configuration for the cxOverstat module

overstat: {
    events: [
        { name: "click", recurseFrames: true },
        { name: "mousemove", recurseFrames: true },
        { name: "mouseout", recurseFrames: true },
        { name: "submit", recurseFrames: true }
    ]
},

TLT.logScreenCapture

This API instructs the underlying native functionality to take a screen capture.

This functionality is only available when a screenCapture callback is registered with the Web SDK by the native code.

Example

if (TLT && TLT.isInitialized()) {
    TLT.logScreenCapture();
}

TLT.logGeolocation

Use this API to log the Type 13 geolocation messages.

if (TLT && TLT.isInitialized()) {  
    TLT.logGeolocation(position);
}

Where position is a object obtained from using W3C Geolocation API getCurrentPosition() function. Refer to the Position interface described in the specification for more information. If the API is called without the standard Position object then the API returns without logging the message.

Example of a Type 13 JSON GeoLocation message logged by this API:

{
    type: 13,
    geolocation: {
        lat: 37.788497,
        long: -122.399935,
        accuracy: 63
    }
}

TLT.logDataLayer(/optional/ Object data)

Use this API to log the application data layer to the Web SDK's message stream. The Web SDK normally logs the data layer after each screenview load. You can use this API to control when to log the application data layer.

Specifying the data object is optional. If you do not specify the data object, then the API logs the data layer object specified in the data layer module configuration.

To disable the automatic logging and assume direct control, do not specify any dataObject in the data layer module configuration. Use this API to supply the desired data object to be logged.

if (window.TLT && TLT.isInitialized()) {
        // Log the application data layer specified in the module configuration.
        TLT.logDataLayer();
    }