Modify Tealeaf events in Advanced mode

Basic mode enables you to create and modify Tealeaf events with UI elements, controls, and data through the Event Manager. Basic mode limits your capability to develop more complex event logic. Advanced mode expands your capability by using JavaScript to modify event logic that would be difficult or impossible in Basic mode.

📘

Note:

The functionality described on this page is unique to TL Saas and is not supported out-of-the-box in TL OnPrem.

Some examples of Advanced mode operations not possible in Basic mode are:

  • String manipulations, such as splitting or concatenation
  • Numeric operations, such as addition, subtraction, or modulus
  • More complex Boolean logic to specify the conditions that the event should record data e.g. (A and B) or (A and C) or (C) or (D).
  • JavaScript object storage for simple or complex data that needs to be accessible between multiple events or hits

Although Basic mode events are created solely with the UI, both modes are producing the same JavaScript that the Tealeaf engine uses for event evaluation. Using Advanced mode simply enables you to use an editor that exposes and allows modification to an event's underlying JavaScript instead of UI-based event manipulation.

📘

Note:

When creating a new event, you must have at least one condition selected to switch from Basic mode to Advanced mode.

Anatomy of a Tealeaf event JavaScript

Let's break down the anatomy of a simple, advanced event.

function E_SAMPLE_EVENT_1234() {
    if ($S.BrowserName.toUpperCase() == “CHROME” &&
        $P["P_BROWSER_ERROR_5678"].patternFound()) {
        $F.setFacts("E_SAMPLE_EVENT_1234");
    }
}
  • function E_SAMPLE_EVENT_1234() - This is the JavaScript function declaration for the event. This function name, which includes its Tealeaf assigned "Internal Name" must not be changed because the event execution engine relies on the generated function name to properly execute the event.

  • $S.BrowserName - Tealeaf has several available JavaScript objects<; $S exposes the Tealeaf session.

  • if (A && B) - The format and contents of this will vary between events, but generally this section is referred to as the conditions because they define the logic that must be true for the event to fire/record data.

  • $P["P_BROWSER_ERROR_5678"] - Like $S, $P is a Tealeaf object that provides access to the customer-defined hit attributes and step attributes (behind the scenes, they are actually patterns/hit attributes) and any data they may have extracted. In the above example, the event is simply using the patternFound() function to determine if any data was found versus other functions that provide access to the actual underlying data.

  • $F.setFacts("E_SAMPLE_EVENT_1234") - This is the actual JavaScript call that denotes the conditions for the event to fire are true and data should be recorded for this instance. Like the event's function line, the event's "Internal Name" is used here to specify which event occurrence we should record.

Parsing numbers and simple mathematical options

Most data extracted in the Basic mode interface is treated as simple text/string; however, it can be useful to convert these strings to numbers to enable other use cases.

function E_MATH_SAMPLE_1234() {
    var subtotal = $P["P_SUBTOTAL_1234"].firstValue();
    var tax = $P["P_TAX_5678"].firstValue();

    //Leverage Tealeaf’s helper functions for local specific parsing
    subtotal = $S.tryParseDouble(subtotal);
    tax = $S.tryParseDouble(tax);

    //Confirm that both variables are numbers
    if (subtotal == null || tax == null)
        return;

    var total = subtotal + tax;

    if (total >= 500) {
        $F.setFacts("E_MATH_SAMPLE_1234");
    }
}

While parseInt and parseFloat are commonly used JavaScript functions, both require clean inputs, which can be difficult to achieve and problematic. The Tealeaf $S.tryParseDouble function makes an initial pass to clean the string (identify the first numeric component, ignore characters, such as whitespace or currency symbols) and then attempts to parse the number based on the system's current understanding of the page/data's locale. Tealeaf attempts to set the session/data locale based on headers, metatags, and device information.

For example, the following values should all parse to 1234.567 for the en-US locale:

  • "1234.567"
  • "$1234.567"
  • "$1,234.567"
  • "abc$1234.567abc123"
  • "#?^abc$1234.567abc123"
  • "#?^abc$1234.567 123"
  • "1234.567"
  • " $ 1234.567 "
  • " $ $1234.567 "

Publishing event data to Acoustic Exchange

You can build your own event that publishes event data to Acoustic Exchange, with Advanced eventing. See Publishing event data from Tealeaf to Acoustic Exchange

Temporary variable/object storage

Using event or session attributes to store or share temporary data adds unnecessary clutter and overhead throughout your system. The following sample provides a cleaner, more flexible option to store and share data between events. Even storing primitives (number, string, etc.), $S.getCustomJSObj and $S.setCustomJSObj calls should use proper JavaScript objects defined with { }.

function E_OBJECT_STORAGE_1234() {
    //Retrieve a local copy of the stored object for the current session
    var jsObj = $S.getCustomJSObj("myUniqueObectKey");

    //null will be returned if no object had previously been stored for the session
    if (jsObj == null) {
        //Initialize a new object if one has not yet been stored for this session
        jsObj = {};
        jsObj.name = "Sample string";
        jsObj.count = 0;
        jsObj.msgs = [];

        for (var i = 0; i < 10; i++) {
            jsObj.msgs.push("value1");
            jsObj.msgs.push(2);
        }
    }

    //Any time the local object is changed, it must be stored for those changes to persist
    jsObj.count += 1;
    $S.setCustomJSObj("myUniqueObectKey", jsObj);

    if (jsObj.count == 10) {
        $F.setFacts("E_OBJECT_STORAGE_1234");
    }
}

$S.getCustomJSObj and $S.setCustomJSObj use JSON to serialize objects, so all stored objects must be represented in JSON. Because of this, the object must be stored via $S.setCustomJSObj each time modifications are made to it. Each user session has a unique custom object repository so that the object key used to store and retrieve data needs to only be unique within a single session and not unique across all sessions. It's worth noting that each store object has a size limit (multiple kilobytes, imposed by calculating the size of the object's JSON representation), but the limit is high enough to handle most use cases. $S.setCustomJSObj returns true if an object was stored successfully, and it returns false if the object fails to convert to JSON or if the resulting object exceeded the object size limit.

Reference value override

An event's reference value is both a variable that other events can access and a mechanism that can populate session attributes and other event objects. The Basic mode UI enables you to set the event's reference value from another event value or a constant, but it can be necessary to manually set that value via an advanced event. In the following sample, the event extracts a user's cart total from one of two potential locations. Rather than have two separate events that need to handle each scenario independently, we can leverage an advanced event to handle them in one place.

function E_REFERENCE_VALUE_OVERRIDE_1234() {
    var referenceValue = null;

    var primary = $P["P_CART_TOTAL_1234"].firstValue();
    if (primary.length > 0) {
        referenceValue = primary;
    } else {
        var secondary = $P["P_CART_TOTAL_5678"].firstValue();
        if (secondary.length > 0) {
            referenceValue = secondary;
        }
    }

    if (referenceValue != null) {
        $F.setFacts("E_REFERENCE_VALUE_OVERRIDE_1234", referenceValue);
    }
}

Most events can simply use the $F.setFacts and only supply a single first argument (the event's internal name), but additional $F.setFacts variants allow for more functionality. The event's internal name is accessible on the Event Manager's event details screen. The reference value override provides $F.setFacts as the second argument. Both numbers and text can be supplied, but all text truncates at 256 characters.

📘

Note:

Setting an event's reference value via JavaScript precedes whatever may be configured in the UI.

Geographic distance calculations

The Tealeaf web application has several location-based features, but none leverage the concept of distance. The following sample calculates the approximate distance between the user's physical location determined by GPS and the user's IP address location.

function E_GEO_DIST_1234() {
    //Calculated using a frequently updated IP to location information database
    var ipLocation = $S.LocationIP;
    //Calculated using the last GPS coordinates captured by the TL SDK    
    var latlonLocation = $S.LocationLatLon;

    //If a particular location is unavailable, a placeholder object will be returned with empty values
    if (ipLocation.Country.length == 0 || latlonLocation.length == 0)
        return;

    var distance = $G.calculateDistance(ipLocation, latlonLocation, “miles”);

    //If invalid inputs are provided or if the distance calculation fails, a -1 or 0 will be returned
    if (distance <= 0)
        return;

    if (distance > 1000) {
        $F.setFacts("E_GEO_DIST_1234");
    }
}

Mobile devices and tablets with built-in GPS receivers provide relatively accurate latitude and longitude coordinates, but desktop and laptop computers without GPS receivers can also return GPS coordinates as well. These coordinates correspond to a Wi-Fi access point or a local endpoint for the user's internet service provider. IP to location lookups have a degree of error that should be considered whenever leveraging their data.
In the sample, the logic calculates the physical distance between the IP and Geo (lat/lon) locations of the current session. Given the likelihood for inaccuracies, any logic leveraging these distances should look at large distances (hundreds or thousands of miles) but should also be considered as an indicator (for usage of a VPN service, fraud, etc.) to trigger further analysis.

Dimension value overrides

The Event Manager UI only allows dimensions to populate by other event objects in the system. This can be limiting if the value intended for a dimension isn't readily available by one of the other event objects (event reference value, session attribute, hit attribute, etc.). Often that value is available in Advanced mode (possibly because it needs cleaned up or derived) and the following sample illustrates how to manually set the dimension value(s) to associate with this event occurrence.

function E_DIM_VALUE_OVERRIDE_1234() {
    var dimOverrides = {};
    dimOverrides["DIM_CUSTOM_123"] = "Hello";
    dimOverrides["DIM_CUSTOM_456"] = "World";

    //All events should only fire conditionally
    //This condition here for consistency but is otherwise irrelevant to this sample
    if ($S.BrowserName.toUpperCase() == “CHROME”) {
        //Passing a null reference value to instruct the event to still pull the UI configured reference value
        var referenceValue = null;
        $F.setFacts("E_DIM_VALUE_OVERRIDE_1234", referenceValue, dimOverrides);
    }
}

The dimension's internal name (accessible on the Event Manager's dimension details screen) identifies the dimension value overrides. The dimension override logic is straightforward, but here are a few implementation details worth noting:

  • Dimensions still populate by a source, even if the dimension will always be manually overwritten in advanced events. The best workaround is to define and populate the dimension(s) with a session attribute or hit attribute that will never populate.
  • Dimension value overrides still have the 256 character dimension value length limit (larger values truncate to size).
  • Dimensions configured to populate at session end still update at session end and are not good candidates for this override functionality.
  • As with all dimensions, the values provided should not be unique (e.g. timestamps, search queries) but should instead be values that aggregate well.
  • All value overrides are assigned to the event occurrence as-is. If the dimension is a text or group list dimension, $F.evaluateDimensionMapping and $F.getDimWhitelistValue may be used to retrieve the appropriate mapping/list item.

Regular expressions in Advanced mode

While hit attributes support regular expressions for extracting text, there may be use cases where a regular expression (regex) is required in Advanced mode. Based on the rate at which events execute, the following sample illustrates where to define a custom regular expression for maximum efficiently.

var eCustomRegex1234_regex = new RegExp("\\d{10}");

function E_CUSTOM_REGEX_1234() {
    // Order number: 1234567890
    var orderNumber = $P["P_ORDER_NUMBER_1234"].firstValue();
    if (orderNumber.length == 0)
        return;

    var matches = orderNumber.match(eCustomRegex1234_regex);
    if (matches.length == 0)
        return;

    orderNumber = matches[0];
    $F.setFacts("E_CUSTOM_REGEX_1234", orderNumber);
}

Functionally, a regular expression defined inside or outside a function behaves the same. The major difference is in performance. Regular expressions defined outside the scope of the function compiles once and is reused in every subsequent function call. Regular expressions or similar logic defined inside a function can recreate (recompile) on every execution and hurt performance.

Updating and retrieving Session Attributes

User-defined session attributes can be set and retrieved in the Advanced mode JavaScript. The following event sample triggers the first time an email address is successfully extracted.

function E_SESSION_ATTR_1234() {
    var storedEmail = $S.getCustomVar("SSV_1234");
        if (storedEmail.length > 0)
            return;

        var extractedEmail = $P["P_EMAIL_1234"].firstValue();

        if (extractedEmail.length > 0) {
            $S.setCustomVar(“SSV_1234”, extractedEmail);
            $F.setFacts("E_SESSION_ATTR_1234", extractedEmail);
        }
    }

Session attributes are set and retrieved using an internal name that is accessible from the Event Manager's session attribute details screen. Although Advanced mode can store longer than usual custom attributes, you should follow the standard limit size of 256 characters. Other parts of the system may impose this limit and produce undesirable results otherwise.

📘

Note:

The Basic mode event > session attribute flow DOES have a hard limit of 256 characters.

Sequence events

It is useful to create an event condition based on other events. Basic mode provides some functionality (e.g. "Exist on Hit" and "Exists on Step"), but more specific conditions are constructed in Advanced mode. The following sample tracks the current shopping cart subtotal when a credit card validation fails when the expiration date information is entered before the credit card number.

function E_SEQUENCE_1234() {
    //If this event has not detected a credit card validation error, there is no reason to proceed
    if (!$P["P_CC_VALIDATION_ERROR_1234"].patternFound() ||
        $F.getEventCount(“E_CC_NUMBER_ENTERED_1234”) == 0 ||
        $F.getEventCount(“E_CC_EXPIRATION_ENTERED_1234”) == 0) {
        return;
    }

    var ccExpirationEntered = $F.getLastFact(“E_CC_EXPIRATION_ENTERED_1234”);
    var ccNumberEntered = $F.getLastFact(“E_CC_NUMBER_ENTERED_1234”);

    //If the expiration information arrived on a later hit than the number, we can stop here
    if (ccExpirationEntered.HitNumber > ccNumberEntered.HitNumber)
        return;

    //If the expiration information occurred on an earlier hit, we know it occurred first
    var sequenceFound = ccExpirationEntered.HitNumber < ccNumberEntered.HitNumber;

    //If the events fired on the same hits, likely in different SDK steps,
    //we need to confirm the order
    if (!sequenceFound) {
        seqFound = ccExpirationEntered.HitNumber == ccNumberEntered.HitNumber &&
            ccExpirationEntered.StepNumber < ccNumberEntered.StepNumber;
    }

    if (sequenceFound) {
        var cartSubtotal = $P["P_CART_SUBTOTAL_1234"].firstValue();
        if (cartSubtotal.length == 0)
            cartSubtotal = 0;

        $F.setFacts("E_SEQUENCE_1234", cartSubtotal);
    }
}

Each recorded fact (event occurrence) is tagged with both the hit number (HitNumber) and the step number (StepNumber) where it occurred. Because all data for a Tealeaf session processes sequentially, these two attributes can be used to establish order between two or more events. This example only properly handles the specific pattern where each event occurs once in a session, but more complex implementations can be written to allow for more complex scenarios.

Tealeaf JavaScript objects

Session - $S

The JavaScript interface to the current session

Fields

📘

Note:

For Mobile applications, the Tealeaf SDKs attempt to retrieve and send a representative UserAgent string to derive some fields. Many UserAgent or device-derived fields may be unavailable if a device cannot provide sufficient context.

For fields that are impacted by synthetic full DOM capture hits, the full DOM capture SDK steps are extracted at ingest and separated into dedicated synthetic hits to simulate a network capture hit.

TypeNameDescription
StringAppKeyThe first AppKey associated with this session. Even if the AppKey changes for a TLTSID, the first AppKey is used for all data storage.
StringTLTSIDSession unique identifier
StringIPClient IP address
StringReferrerThe referrer URL from the first hit of the session
StringReferrerDomainThe referrer domain from the first hit of the session
StringUserAgentBrowser user agent
StringBrowserNameBrowser name
StringBrowserVersionBrowser version
StringOSOperating system name
StringOSVersionOperating system version
StringPlatformDevice platform classification. Possible values: IOS, ANDROID, MOBILE_WEB, DESKTOP_WEB, BOT.
Int64StartTimeEpochEpoch time for the first hit of the session as observed by the Tealeaf system
Int64LastHitEpochEpoch time for the last/latest hit of the session as observed by the Tealeaf system.
StringFirstURLThe first hit URL of the session (will be the Tealeaf Collector URL for SDK hits). The best practice is to use FirstScreenView.
StringLastURLThe last/latest hit URL of the session (will be the Tealeaf Collector URL for SDK hits). The best practice is to use LastScreenView.
StringFirstScreenViewThe ScreenView name for the first hit of the session. Derived from the ScreenView LOAD step or page information for an SDK hit or the actual request URL for a network (hybrid or CDN) hit.
StringPreviousScreenViewThe ScreenView name for the previous hit of the session
StringLastScreenViewThe ScreenView name for the last/latest hit of the session
Int64ClientDurationThe duration in seconds derived from the SDK step timestamps
Int64ServerDurationThe duration in seconds derived from hit timestamps
Int64DurationPresently the same as ServerDuration
Int32NumberOfHitsThe total number of hits (including the current hit). This count tracks the number of network and SDK hits, and it is currently inflated by the number of full DOM captures.
Int32ScreenViewCountTotal number of ScreenView LOAD steps and number of licensed network hits
Int32SDKMessageCountTotal number of received SDK steps (aka SDK messages)
Int64TotalREQBytesThe current byte count total for all requests, impacted by synthetic full DOM capture hits
Int64TotalRSPBytesThe current byte count total for all responses, impacted by synthetic full DOM capture hits
Int32EventCountCurrent count of events generated for the current session
Int32FactCountCurrent count of facts (event and dimension group combinations) generated for the current session
Int32UBXEventCountCurrent count of UBX events generated for the current session
Int32OrientationChangesThe number of times the device orientation was changed
StringOrientationDominantThe device orientation that is used the longest. Possible values: PORTRAIT, LANDSCAPE, an empty string.
StringLanguageThe English US display name for the current session's locale (derived from available information)
StringTealeafSDKTypeIdentifier denoting what SDK (if any) generated the current hit. Possible values: None, UIC, iOS, Android.
StringTealeafSDKVersionIf applicable, the Tealeaf SDK version
GeolocationLocationIPSession location information derived from the client's IP address
GeolocationLocationLatLonSession location information derived from the Type 13 SDK steps (lat/lon coordinates)
GeolocationLocationInitially populates with the LocationIP, but updates to match LocationLatLon if lat/lon coordinates are received.
StringDeviceThe device classification. Possible values: Tablet, MobilePhone, Desktop.
StringDeviceVendorThe device vendor, UserAgent derived
StringDeviceModelThe device model, UserAgentderived
StringDeviceManufacturerThe device manufacturer, UserAgent derived
StringDeviceMarketingNameThe device marketing name, UserAgent derived
Int32DeviceYearReleasedThe device year released, UserAgent derived
BooleanIsMobileDeviceThe device is a mobile device, UserAgent derived
BooleanIsTouchScreenThe device is a touch screen device, UserAgent derived
BooleanIsMobilePhoneThe device is a mobile phone, UserAgent derived
BooleanIsTabletThe device is a tablet, UserAgent derived
BooleanIsBotBot identifier, determined by the supplied browser UserAgent
StringMobileNetworkReachabilityThe mobile device network status. Possible values: NotReachable, ReachableViaWiFi, ReachableViaWWAN
StringMobileAppNameThe native mobile application name
StringMobileAppVersionThe native mobile application version
Int32MobileExceptionsThe current count of mobile application exceptions

Methods

Return type

Name

Description

Parameters

Returns

Boolean

setCustomJSObj(String name, Object value)

Stores a custom JavaScript object within the current session

name - the unique key for the object
value - the JavaScript object to store (will convert to JSON)

A flag denoting the success of the set call

Object

getCustomJSObj(String name)

Retrieves a custom JavaScript object from the current session

name - the unique key for the object

The JavaScript object (evaluated from the stored JSON), null on failure

Boolean

setCustomVar(String sessionAttributeInternalName, String value)

Sets the value of a user defined session attribute (aka session state variable)

sessionAttributeInternalName - the internal name for the session attribute, accessible from the Event Manager's session attribute details screen
value - the value to store

A flag denoting the success of the set call

String

getCustomVar(String sessionAttributeInternalName)

Retrieves the value of a user defined session attribute (aka session state variable)

sessionAttributeInternalName - the internal name for the session attribute, accessible from the Event Manager's session attribute details screen

A flag denoting the success of the set call

Double

tryParseDouble(Object input)

Cleanses and converts an input string to a number tryParseDouble makes an initial pass to clean the string (identify the first numeric component, ignoring characters such as whitespace or currency symbols) and then attempts to parse the number based on the system's current understanding of the page/data's locale. Tealeaf attempts to set the session/data locale based on headers, meta-tags, and device information.
For example, the following values should all parse to 1234.567 for the en-US locale:

  • 1234.567
  • $1234.567
  • $1,234.567
  • abc$1234.567abc123
  • #?^abc$1234.567abc123
  • #?^abc$1234.567 123
  • 1234.567
  • $ 1234.567
  • $ $1234.567
input - the value to be parsed; the provided value is typically a string but the function will accept and return numeric values as wellThe converted number, null on failure
BooleanhasSeenAppKey(String appKey)All data for a session is associated with the first AppKey received for a session, but internally we track all AppKeys sent for a session and can expose them if a session sent data for a particular AppKeyappKey - the Application Key (AppKey) in questionA flag denoting if the AppKey has been seen for the current session

Hit - $H

The JavaScript interface to the current hit

Fields

📘

Note:

While full DOM capture SDK steps extract into dedicated synthetic hits at the point of ingest, DOM diff steps remain embedded in the SDK JSON. However, Tealeaf simulates a synthetic hit for each DOM diff during eventing. As an SDK hit's steps process, each DOM diff occurrence loads into a simulated hit and all hit level hit attributes and events (Every Hit, After Every Hit) execute in an isolated space (not impacted by the source SDK hit).
$H.IsDomCaptureHit and $H.IsDomDiffHit allow for Advanced events to differentiate between hit types to only fire under the intended conditions.

📘

Note:

DOM diff is supported only in Tealeaf SaaS. In Tealeaf On-premises, DOM diff is supported for web-only and not supported for replaying Hybrid Mobile apps.

TypeNameDescription
StringTLTHIDThe hit unique identifier
Int32HitNumberThe hit number
StringURLThe hit URL (is the Tealeaf Collector URL for SDK hits)
Int32StatusCodeThe response status code, only relevant for network hits
StringContentTypeThe response content type
StringQueryStringThe request query string
StringReferrerThe request referrer
Int32ReqSizeThe request byte count
Int32RspSizeThe response byte count
BooleanIsDomCaptureHitThe hit is a full DOM or DOM diff hit, DOM diff doesn't use synthetic hits
BooleanIsDomDiffHitIs the hit a DOM diff hit, DOM diff doesn't use synthetic hits

Methods

Return typeNameDescriptionParametersReturns
StringgetUrlArg(String name)Provides access to the page's URL arguments. For Web SDK hits, the URL information extracts from the SDK hit's web environment section.name - The URL argument name (case-insensitive)The requested URL argument, an empty string returns for missing arguments
StringgetUrlFragment()Provides access to the page's URL fragment (aka hash value). For Web SDK hits, the URL information extracts from the SDK hit's web environment section.N/AThe URL fragment, an empty string returns if no fragment is present
StringgetCookie(String name)Provides access to a single collection containing both the HTTP request and HTTP response cookies (when available). For UI SDK hits, a client-derived "cookies" step is sent with what cookies can be extracted from the client.name - Cookie name (case-insensitive)The requested cookie, an empty string returns for missing cookies
StringgetHeader(String name)Provides access to a single collection containing both the HTTP request and HTTP response HTTP headers (when available).name - The HTTP header name (case-insensitive)The requested header, an empty string returns for missing headers

Pattern collection - $P

A collection of functions for interfacing with pattern (customer-defined hit attribute) data

Methods

Return typeNameDescriptionParametersReturns
PatternDatagetPatternData(String patternInternalName)Provides access to extracted pattern/hit attribute datapatternInternalName - The internal name for the pattern, accessible on the Event Manager's hit attribute details screenA PatternData object containing all the extracted values, an empty PatternData returns even when there are no matches. PatternData.patternFound() == false or PatternData.matchCount() == 0 can be used to check for an empty PatternData.
PatternData$P[patternInternalName]See getPatternData(patternInternalName)N/AN/A

Fact collection - $F

A collection of functions for interfacing with fact (the results of event execution) data.

Methods

Return typeNameDescriptionParametersReturns
FactgetFirstFact(String eventInternalName)Provides access to the first event/fact occurrence in the current sessioneventInternalName - The internal name for the event, accessible on the Event Manager's event details screenA Fact object containing all the Fact occurrence, an empty Fact returns if the event did not fire. Fact.EventID == -1 can be used to check for an empty Fact.
FactgetLastFact(String eventInternalName)Provides access to the last/latest event/fact occurrence in the current sessioneventInternalName - The internal name for the event, accessible on the Event Manager's event details screenA Fact object containing all the Fact occurrence, an empty Fact returns if the event did not fire. Fact.EventID == -1 can be used to check for an empty Fact.
Int32getEventCount(String eventInternalName)Provides access to the number of times an event fires in the session; the number of associated dimension groups does not impact this count.eventInternalName - The internal name for the event, accessible on the Event Manager's event details screenThe current event count in the current session
BooleansetFacts(String eventInternalName)Records an event/fact occurrenceeventInternalName - The internal name for the event, accessible on the Event Manager's event details screenReturns true/false to denote whether or not the setFacts call was successful
BooleansetFacts(String eventInternalName, Object referenceValue)Records an event/fact occurrence. This method accepts a reference value override if a non-null takes precedence over the reference value data source configured in the Event Manager UI.eventInternalName - The internal name for the event, accessible on the Event Manager's event details screen
referenceValue - The reference value associated with this event occurrence. If a null reference value is provided, the data source configured in the UI is used.
Returns true/false to denote whether or not the setFacts call was successful
BooleansetFacts(String eventInternalName, Object referenceValue, Object dimValues)Records an event/fact occurrence. This method accepts a reference value override if a non-null takes precedence over the reference value data source configured in the Event Manager UI. It also accepts dimension value overrides that are used to replace the dimension value inputs for each of the associated dimension groups.eventInternalName - The internal name for the event, accessible on the Event Manager's event details screen.
referenceValue - The reference associated with this event occurrence. If a null reference value is provided, the data source configured in the UI is used. Both string and numeric values are accepted.
dimValues - A JavaScript object with the dimInternalName: dimValueOverride mappings. For example, { “DIM_CUSTOM_123” : “Hello”, “DIM_CUSTOM_456” : “World” }
Returns true/false to denote whether or not the setFacts call was successful
StringgetDimWhitelistValue(String dimInternalName, String value)Evaluates the value to whitelist value mapping logicdimInternalName - The internal name for the dimension, accessible on the Event Manager's dimension details screen
value - The input value
The corresponding whitelist value, null returns if the value is not in the whitelist.
StringevaluateDimensionMapping(String dimInternalName, Object value)Evaluates the value to the group list (including both text lists and numeric ranges) mapping logicdimInternalName - The internal name for the dimension, accessible on the Event Manager's dimension details screen
value - The input value
The corresponding mapping value, the dimension's default value returns if no mapping is available.

Geolocation library - $G

A collection of functions for retrieving and interacting with geolocation information

Methods

Return typeNameDescriptionParametersReturns
DoublecalculateDistance(String srcLat, String srcLon, String dstLat, String dstLon, String units)Calculates the distance between two sets of longitude and latitude coordinates. Calculations perform using the Haversine formula and use the Earth's mean radius for all calculations.srcLat - Source latitude
srcLon - Source longitude
dstLat - Destination latitude
dstLon - Destination longitude
units - Units for the return value, possible values: miles, kilometers
The distance between the two sets of coordinates in the specified units. A return value <= 0 denotes an error (invalid coordinates or an invalid unit was provided)
DoublecalculateDistance(double srcLat, double srcLon, double dstLat, double dstLon, String units)Calculates the distance between two sets of longitude and latitude coordinates. Calculations perform using the Haversine formula and use the Earth's mean radius for all calculations.srcLat - Source latitude
srcLon - Source longitude
dstLat - Destination latitude
dstLon - Destination longitude
units - Units for the return value, possible values: miles, kilometers
The distance between the two sets of coordinates in the specified units. A return value <= 0 denotes an error (invalid coordinates or an invalid unit was provided)

PatternData

The return value from $P.getPatternData(patternInternalName) and $P[patternInternalName] containing the pattern matches from the user defined hit attribute.

Methods

Return typeNameDescriptionParametersReturns
BooleanpatternFound()A quick check to determine if the pattern/hit attribute has any matches; it is functionally the same as PatternData.matchCount() > 0N/AA Boolean denoting whether or not the PatternData contains any matches
Int32matchCount()The number of pattern/hit attribute matchesN/AThe number of pattern/hit attribute matches
StringfirstValue()Provides access to the first pattern/hit attribute matchN/AThe first pattern/hit attribute, an empty string returns if the PatternData has no matches to return
StringlastValue()Provides access to the first pattern/hit attribute matchN/AThe last pattern/hit attribute match, an empty string returns if the PatternData has no matches or if an invalid index is requested
StringvalueAt(Int32 index)Provides access to a specific pattern/hit attribute matchindex - The 0-based index of the match/value to returnReturns the match/value at the specified index, an empty string returns if the PatternData has no matches or if an invalid index is requested

Fact

The return value from $F.getFirstFact(eventInternalName) and $F.getLastFact(eventInternalName) containing the context of the event occurrence instance, including the reference value.

Fields

TypeNameDescription
Int32EventIDEvent ID
Int32FactIDFact ID
StringTLTHIDHit unique identifier
Int32HitNumberHit number
Int32StepNumberHit step number
Int64HitTimeEpochHit epoch time
DoubleNumericValueThe numeric Reference Value of an event if the Reference Value is populated and configured as Numeric. Internally, this uses $S.tryParseDouble.
StringValueThe text Reference Value of an event. For Numeric Reference Value events, this text contains the original input text before the numeric value is extracted.

Geolocation

The return value from several $G functions, as well as $S.Location, $S.LocationIP, and $S.LocationLatLon attributes containing any geographic information Tealeaf is able to derive for the session.

Fields

TypeNameDescription
StringContinentContinent name, possible values: Africa, Antarctica, Asia, Australia, Europe, North America, Oceania, South America
StringCountryCodeCountry code, standard: ISO-3166
StringStateState/province name
StringCityCity name
StringPostalCodeCity postal code
DoubleLatLatitude
StringLonLongitude

Additional notes and tips

  • Session attribute values truncates to 256 characters.
  • Dimension value data sources should always aggregate well, e.g. do not use search terms or other text entered by users.
  • Dimension values truncate to 256 characters.
  • If an event has no need to be searchable or reportable, meaning it only exists to service other events, the Building block only option should be used.
  • Code defensively. Advanced mode events should use null checks and try/catch blocks appropriately.
  • Avoid introducing infinite or nested loops in Advanced events because they may slow down or even stop data processing.
  • Advanced mode cannot enforce an event to only conditionally fire, but events should almost never fire on every hit/step/etc.
  • When building hit attributes, ensure the start/end tags are unique to limit the number of potential matches. Generic matches like <div> and </div> may match too many values and introduce performance issues.
  • When designing regular expressions for hit attributes, take care to avoid .*, .+, etc. whenever possible. The more variability in a regular expression, the longer each evaluation may take.
  • When creating step attribute paths for SDK data extraction, avoid paths that may contain some variability. For example, making a reference to the third cild div may be unreliable if other divs come and go (like a shopping cart).
  • Don't forget to test the negative case for events
  • The terms step and message are both used to describe the data elements in the Tealeaf SDK JSON
  • Although event and fact are often used to describe the same concept, they are technically very different. The event is the core definition/logic and the fact is the data element or record produced by an event. All events produce a single fact to track the base event count and an additional fact for each associated dimension group to track the specific event and dimension group combinations, i.e. $F.getFirstFact and $F.getLastFact