Mobile Apps WebView tracking

Last updated on

To enable WebView tracking and Session Replay in your mobile app, you need to implement the Contentsquare Web Tracking Tag in every web page called in your mobile app for the WebView to communicate with our native SDK.

WebView tracking relies on:

Getting Started

The Web Tracking Tag is responsible for establishing communication with the SDK in the parent app.

To set it up, add the following code on every page that will be called in a WebView of your app.

Add it either at the end of the body marker or via a TMS.

Replace YOUR_TAG_ID with the tag ID of your project provided by Contentsquare.

<script type="text/javascript">
  (function () {
    window._uxa = window._uxa || [];
    window._uxa.push(["setOption", "isWebView", true]);
    var mt = document.createElement("script");
    mt.type = "text/javascript";
    mt.async = true;
    mt.src = "https://t.contentsquare.net/uxa/YOUR_TAG_ID.js";
    document.getElementsByTagName("head")[0].appendChild(mt);
  })();
</script>

Handling Web & WebView contexts

This code creates a function that adds an asynchronous call to a script and then executes it. This helps to prevent other elements on the page from being blocked, reducing the impact of the tag on the page's performance.

To use the same tracker for both the Web and WebView use cases, include a conditional statement:

if (aConditionThatTellsYouWeAreInAWebview())
   window._uxa.push(['setOption', 'isWebView', true]);
else
   // do nothing if it's a web browser

Privacy

While we strongly recommend to handle opt-in and opt-out from the native side, there may be cases where you would prefer to handle it from the WebView. This is why we are providing opt-in/opt-out commands on the web tracking tag. However keep in mind that opting in/out from the WebView will opt-in/out the user on the native side as well.

If you choose to handle user consent from the WebView, we remind you that you are responsible for creating the UI asking users for their consent and allowing them to manage their privacy settings and then calling the appropriate Contentsquare following methods (optin or opt-out).

Opt-in from the WebView

Use the Opt-in API to get user consent. Calling this API generates a user ID and initiates tracking.

window._uxa = window._uxa || [];
window._uxa.push(["optin"]);

Opt-out from the WebView

Permanently breaking the link and stopping all data collection.

When this API is called, tracking stops immediately, all settings are reset (Session number, Page number...) and all files and directories regarding Contentsquare are deleted. This means that the user ID is deleted. The SDK will never track or collect any data from the user's phone unless the Opt-in API is called again.

window._uxa = window._uxa || [];
window._uxa.push(["optout"]);

Track Pageviews

To aggregate user behavior and engagement at the screen/page level, track page transitions by calling the trackPageview command.

window._uxa = window._uxa || [];
window._uxa.push(["trackPageview", "PAGE_TITLE_OR_URL"]);

The Web Tracking Tag logs a pageview event that identifies the new page with the page title that you provide.

Track pageviews differences (WebView vs Web)

Tracking Pageviews has different rules depending on the context: in web or WebView.

No natural pageview in WebView mode

When set in WebView mode (isWebView not set or set to false), the tracking tag will not trigger (web) natural pageviews. If you rely on a natural pageview when the page is loaded from a web browser, make sure to use the trackPageview when loaded in WebView mode. Example:

<script type="text/javascript">
  (function () {
    window._uxa = window._uxa || [];
    if (aConditionThatTellsYouWeAreInAWebview()) {
      window._uxa.push(['setOption', 'isWebView', true]);
      window._uxa.push(["trackPageview", "PAGE_TITLE_OR_URL"]);
    } else  { 
      // Tag will trigger a natural pageview in web context
    }
    var mt = document.createElement("script");
    mt.type = "text/javascript";
    mt.async = true;
    mt.src = "https://t.contentsquare.net/uxa/YOUR_TAG_ID.js";
    document.getElementsByTagName("head")[0].appendChild(mt);
  })();
</script>

trackPageview command differences

The trackPageview command is also used to send an artificial pageview in web context. However the page title/URL setup behaves differently:

  • In WebView mode, the value you set is the one that will be seen in the Contentsquare platform (while in web context, the tag will prepend the value with the domain and append it with the query parameters).
  • In WebView mode, if no value (second array element) is provided, no default value will be provided (while in web context, the tag will set the path as default value).

Track Transactions

To associate a user's session with their potential purchases (and corresponding revenue), you must send the transaction via a dedicated API. For each transaction, we send:

  • Price (mandatory)
  • Currency (mandatory)
  • Transaction ID (optional)
window._uxa = window._uxa || [];
window._uxa.push([
  "ec:transaction:create",
  {
    id: "123" /* Transaction ID (string, up to 40 chararacters) */,
    revenue:
      "9.99" /* Transaction's total cost (integer or string, up to 12 digits and 2 decimals - extra decimals are truncated) */,
    currency:
      "usd" /* optional - Currency value (string, numeric or alphanumeric ISO 4217 value) */,
  },
]);
window._uxa.push(["ec:transaction:send"]);
// value is a float
// currency is a string that must be inferior to 10 characters
// id is a string or null

Currency

The currency is conforming to the ISO 4217 standard.
The currency must be passed as an "alphanumeric code".

If the currency doesn't match the supported currencies, the SDK sends a currency value of -1.
It will be processed as the default currency of the project.

Track Dynamic Variables

General principles

Usage

Dynamic variables are additional information on the session that can be used to segment sessions.

For example, they can include information on the A/B Test variations displayed to the current user.

Limits

On the server side
  • It is possible to save up to 40 distinct dynamic variable keys per screenview. If more are received, only the first 40 keys will be kept.
  • If you are using the same key twice on the same screenview, the last value associated with the key will be collected.
On the SDK side
  • Every dynamic variable is composed of a pair of key (max. 50 characters) and value (max. 255 characters string or number of type Long between 0 and 232 - 1). In case these maximum lengths are reached, the SDK will automatically trim the exceeding characters.
  • If key or value are empty, the SDK will instead send the literal string "cs-empty".

Defining dynamic variables

To define and send a dynamic variable, directly use the key and String/Long value once a first screenview has been triggered:

window._uxa = window._uxa || [];
window._uxa.push(["trackDynamicVariable", { key: my_key, value: my_value }]);
// key is a string
// value is either a string or an integer

Type of the value — The value can be either a whole number or a string. For each case, available features won't be the same in the Contentsquare app:

  • For whole numbers, you will be able to do some algebra. Example: sessions with dynamic variable key = "numberOfFriends" and value >= 10_
  • For strings, auto-completion and Regular Expression will be available. Example: sessions with dynamic variable key = "accountType" and value = "Premium"

Collected data

Once communication is established, the tag will start tracking the following events and pass them over to the SDK:

  • Pageviews manually triggered (with the dedicated command)
  • Transactions manually triggered (with the dedicated command)
  • Dynamic variables manually triggered (with the dedicated command)
  • Gestures automatically detected: tap, double tap, swipes (with finger direction), pinches (in and out)
  • HTML DOM and DOM Mutation when session replay is activated
  • HTML DOM when a snapshot of the screen is triggered by the SDK (see Enable Snapshot Mode in iOS and Android docs).

Session Replay

Personal Data Handling

See Personal Data Handling.

Choosing a Data Collection Strategy

There are multiple options for collecting data, and the strategy that is best for you will depend on various factors.

Some questions to consider include:

  • Is the WebView page also visited by web browsers, or is it only used within a WebView context?
  • Are the same teams responsible for these pages in both contexts (on the website and within a mobile app webview), or do different teams work closely together and share a lot of code?
  • Does most of the tracking customization need to apply in both contexts (with little to no differences), such as session replay masking rules and event handling?

Migration from the WebView Tracking Tag

To migrate from the WebView Tracking Tag to the Web Tracking Tag, follow these steps:

  1. Update the Tag

    Replace the WebView Tracking Tag:

    //t.contentsquare.net/wvt/web-view.js

    With the Web Tracking tag of your project (either a new tag or the one from a Web project):

    //t.contentsquare.net/uxa/YOUR_TAG_ID.javascript
  2. Update pageview tracking

    Replace the current trackPageview command:

    window.cs_wvt.push(["trackPageview", "My Custom Page Title"]);

    With:

    window._uxa.push(["trackPageview", "My Custom Page Title"]);

    📚 See more about the trackPageview command.

  3. Update the transaction tracking

    Replace the legacy WebView Tracking Tag transaction command:

    window.cs_wvt.push([
      "trackTransaction",
      { value: 1000, currency: "EUR", id: "my-transaction-id" },
    ]);

    With the transaction commands from the Web Tracking Tag:

    //Create the transaction
    window._uxa.push([
      "ec:transaction:create",
      {
        id: "123" /* Transaction ID (string, up to 40 chararacters) */,
        revenue:
          "9.99" /* Transaction's total cost (integer or string, up to 12 digits and 2 decimals - extra decimals are truncated) */,
        currency:
          "usd" /* optional - Currency value (string, numeric or alphanumeric ISO 4217 value) */,
      },
    ]);
    //Send the complete transaction
    window._uxa.push(["ec:transaction:send"]);
  4. Update the dynamic variable tracking

    Replace the legacy WebView Tracking Tag dynamic variables command:

    window.cs_wvt.push([
      "trackDynamicVariable",
      { key: "my_key", value: "my_value" },
    ]);

    With the dvar command from the Web Tracking Tag:

    window._uxa.push(["trackDynamicVariable",
      { key: my_key, value: my_value }
    ]);

Compatibility

iOS

Contentsquare allows to track WebViews in your iOS mobile app, when WKWebView is used.
WebViews using SFSafariViewController are not supported: these WebViews are not tracked and not displayed in Session Replay (but the rest of the corresponding sessions is still properly displayed).

Android

Session Replay of WebViews in an Android mobile app isn't supported yet. It means that unmasked WebViews are displayed as images in Session Replay (but the rest of the corresponding sessions is still properly displayed).

Changelog

📚 Web Tracking Tag Changelog