Contentsquare React Native Integration
Get Started
Add Contentsquare to your app
This guide walks you through the process of adding the Contentsquare SDKs to your React Native application. The Contentsquare Bridge for React Native is a bridge between the Contentsquare SDKs for iOS and Android, and your React Native JavaScript code. It allows for the use of our solution both in native and JavaScript parts of your app. The Contentsquare functionality is provided through a simple NPM package including only the bridge and dependencies to specific versions of the SDKs. Check the compatibility section for more information about these dependencies, and the minimum React Native version compatible for each version of the bridge.
Note that our Bridge is fully compatible with TypeScript, and includes a d.ts file in order to get typings within your TypeScript React Native projects when adding the Contentsquare Bridge.
How to include it
Open up a terminal window and navigate to the folder where your application is stored. First, find the latest version of the bridge compatible with your version of React Native using our compatibility table. Then, install the bridge as follows, specifying the exact version you want to install if needed:
npm install @contentsquare/react-native-bridge
cd ios && pod install
iOS specific note
As React Native projects are Objective-C projects for iOS, and our iOS SDK is written in Swift, you will have to embed the Swift standard libraries to your project. To do so, go to the Build Settings
of your project's target, and set the Build Option Embedded Content Contains Swift Code
to YES.
Also, you will have to make sure that your CocoaPods
version is 1.10.0 or up (pod --version
). If it is not, simply do [sudo] gem install cocoapods
.
Why? CocoaPods
is the tool that we use in order to link our SDK and our bridge for iOS on React Native, and having a lower version will make the linking of the both impossible, as the SDK is now embedded in an XCFramework, which were only supported by CocoaPods
in late 2020.
How to import the bridge in your JavaScript code
The Contentsquare module is our main module, as well as the default export of our bridge. The Currency module is only used to send Transactions, and contains all supported currencies (see section Send Transactions).
import Contentsquare, { Currency } from "@contentsquare/react-native-bridge";
Important note about React Native apps with native code
Depending on if you created your app as a React Native first app, or if you gradually added some React Native code to your Native first app, you might be using some non JavaScript elements in your app, as well as a mix of native screens and JavaScript screens. If that is the case, it is your responsibility to track all of the screens, either by calling our native SDKs directly in the first case, or the bridge in the second. The same remark applies for other functionalities of the SDK - for example, you might need to send a Transaction Event via the native SDK or via the bridge, depending on the technology used to create your buying page.
Have a look at the Android and iOS SDKs to find out how to call them in native parts of your app.
Also, note that we specifically cover the use of the JavaScript bridge in this documentation. You should never call the Bridge's NativeModule directly yourself. If for any reason you do so, know that we cannot certify that your implementation will work as expected. Only call our SDKs through the JavaScript Contentsquare module we provide in you JavaScript code (as explained in this document), or directly in your native code.
Start the SDK
You do not need to do anything to start the SDK. Now that the SDK is a dependency of your app, it will autostart itself when your application starts.
Enabling SDK Manual Start
If you prefer to control if and when the SDK starts, you can disable the autostart feature and programmatically start the SDK when needed.
Disabling autostart on iOS
You need to edit the Info.plist
, usually located in ios/{project_name}/
, add the following key:
<dict>
...
<key>CSDisableAutostart</key>
<true/>
...
</dict>
Disabling autostart on Android
You need to edit the AndroidManifest.xml
, usually located in android/app/src/main/
, add the following flag:
<application>
...
<meta-data
android:name="com.contentsquare.android.autostart"
android:value="false"
/>
...
</application>
Programmatically start the SDK
Then, you can start the Contentsquare SDK by calling the start()
method of the Contentsquare
class.
This function should be called as early as possible in the app process. Call this function in the useEffect
of your App element:
const App = (): JSX.Element => {
...
useEffect(() => {
Contentsquare.start()
...
});
...
}
Note about using Contentsquare along with Expo
To use the SDK on an Expo app, you need to have an Expo project with EAS (Expo Application Services). The SDK compatibility with Expo projects requires the extra steps described below.
Configuration
Add the plugin and your Contentsquare bundle identifier to your app configuration file:
{
"expo": {
...,
"ios": {
"bundleIdentifier": "com.cs.expo.app", // replace with your bundle id
...
},
"android": {
"package": "com.cs.expo.app", // replace with your bundle id
...
},
"plugins": [
"@contentsquare/react-native-bridge",
],
}
}
Run
To run your Expo app with the Contentsquare SDK, you can't use Expo Go since it needs native files and features. To run your app, use the following commands:
[tab] iOS
expo run:ios
[tab] Android
expo run:android
[tabend]
Or, you can replace the scripts to your app in your project's package.json
:
"scripts": {
...
"android": "expo run:android",
"ios": "expo run:ios",
},
Validate SDK integration
Look at the native SDK docs for validation on each platform.
In-app features
Alongside its tracking capabilities, the SDKs embed some features aimed at Contentsquare users such as Snapshot Capture and SDK Logs.
Implement in-app features
This implementation phase is required on the iOS side only (on Android, there is nothing to do). You will have to do a few changes on the native side of your app:
1. Add the custom URL scheme to Info.plist
In order for your application to open when you scan the QR code or enter the URL we provide in a web browser, you have to add the custom URL scheme to your app's Info.plist
file. For more info about how to do it, check the iOS documentation.
2. Call the SDK when your app is opened with the custom URL
Then, you will need to link your app with our SDK. When your application is started via a deeplink, a specific delegate function is called in your AppDelegate file. In order for us to be able to handle it, you will need to call a function of our API that will handle it.
There are 2 ways to do so.
1. Call the react native API
Follow this guide to call the react native API.
[tab] JavaScript
Linking.addEventListener("url", (event) => {
Contentsquare.handleUrl(event.url);
});
[tab] TypeScript
Linking.addEventListener("url", (event: { url: string }) => {
Contentsquare.handleUrl(event.url);
});
[tabend]
2. Call the iOS native API
You will need to update your iOS application's AppDelegate, located in the ios
folder of your React Native app (AppDelegate.m if you have a project set up in Objective-C, AppDelegate.swift if it is set up in Swift).
Import ContentsquareModule in order to be able to call the Contentsquare API from the AppDelegate.
â ī¸ If you are using Flipper, make sure you do not write the import after the FB_SONARKIT_ENABLED
macro - to be sure, you can write your import at the topmost of the file. In general, make sure you do not import the SDK in the scope of an #ifdef
macro.
[tab] Objective-C
#import <ContentsquareModule/Contentsquare-Swift.h>
[tab] Swift
import ContentsquareModule
[tabend]
Implement the openURL delegate method as following.
[tab] Objective-C
- (BOOL)application:(UIApplication *)app
openURL:(NSURL *)url
options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options {
[Contentsquare handleWithUrl:url];
return YES;
}
[tab] Swift
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
Contentsquare.handle(url: url)
return true
}
[tabend]
Check the full section in the Native iOS SDK documentation
Enable in-app features
In-app features can be enabled in different ways:
Scan the QR Code
If you have access to the Contentsquare platform, you can open the in-app features modal from the menu and scan the QR code displayed with your phone.
Take a look at the native documentation for further information.
Alternative methods
We provide alternative methods to enable in-app features especially for iOS Simulator and Android Emulator.
[tab] Android
Follow the Native Android SDK documentation for Enable in-app features
[tab] iOS
Follow the Native iOS SDK documentation for Enable in-app features
Debugging and Logging
Contentsquare provides Logging capabilities that allow you to see the raw event data logged by your app. This is very useful for validation purposes during the instrumentation phase of development and can help you discover errors and mistakes in your analytics implementation and confirm that all events are being logged correctly.
[tab] Android
Follow the Native Android SDK documentation for Debugging and Logging
[tab] iOS
Follow the Native iOS SDK documentation for Debugging and Logging
Snapshot Capture
In order to unlock the full data-visualization capabilities of Contentsquare, the SDK provides a way to capture snapshots of your app screens. These snapshots can only be taken by Contentsquare's users on their device. They are not captured from your end-users device. It means your Personal Data is safe, as long as you use a test user account.
[tab] Android
Follow the Native Android SDK documentation for Snapshot Capture
[tab] iOS
Follow the Native iOS SDK documentation for Snapshot Capture
Privacy
The Contentsquare React Native Bridge and SDKs are compliant with the Play Store and App Store Privacy guidelines as well as with the EU General Data Protection Regulation (GDPR).
Consult our Privacy Center and Privacy Policy.
Handling User Consent
Even though Contentsquare only collects usage data on your app, we will consider every new user to be opted-out. To start tracking, the Opt-in API must be called.
Opt-in
Use the Opt-in API to get user consent. Calling this API will generate a user ID and initiate tracking.
import Contentsquare from "@contentsquare/react-native-bridge";
Contentsquare.optIn();
Opt-Out
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, user ID...) and all files related to Contentsquare tracking are deleted. Contentsquare will never track and collect any data from the user's phone unless the Opt-in API is called again.
import Contentsquare from "@contentsquare/react-native-bridge";
Contentsquare.optOut();
Forget me
Permanently breaking the link between the collected data and actual user.
This resets all settings (session number, page number, user ID...) and deletes all files related to Contentsquare tracking from the user's device. If the user is opted in, next time the user starts the app, the SDK will re-start its collection mechanisms as if this was the first ever run for a new user, under a new user ID. Configurations will be fetched from the server and application tracking will be on.
import Contentsquare from "@contentsquare/react-native-bridge";
Contentsquare.forgetMe();
Give me my data
We allow the client to provide to their users their Contentsquare user ID.
This ID is a non binding identifier which can be used to make a data request to Contentsquare. You are able to get an ID only if the user is not Opted-out. To do so, pass a callback as a parameter to the function.
import Contentsquare from "@contentsquare/react-native-bridge";
const [userId, setUserId] = useState("not retrieved yet");
//Contentsquare.getUserId(string => {})
Contentsquare.getUserId((newUserId) => {
console.log(`Your Contentsquare UserID is ${newUserId}`);
setUserId(newUserId);
});
Stop / Resume Tracking
Although we do not gather any humanly readable text from the user's screens, we understand that there may be some areas that you want to completely exclude from tracking. For this reason, we also support stopping and resuming the complete tracking mechanism.
import Contentsquare from "@contentsquare/react-native-bridge";
// Stop tracking
Contentsquare.stopTracking();
// Resume tracking
Contentsquare.resumeTracking();
Track Screens
Contentsquare aggregates user behavior and engagement at the screen level. To do so, it is required to track screen transitions by calling a dedicated API. When the API is called, the SDK logs a screenview event that identifies the new screen with the screen name provided.
import Contentsquare from "@contentsquare/react-native-bridge";
// Contentsquare.send(string);
Contentsquare.send("ScreenName");
Screen name handling
The screen name length is not limited on the SDK side. However, the limit is 2083 characters on the server side.
Screenview after app in background
The SDK triggers a screenview automatically after the app is put in background and foreground, as long as a screenview with a screen name has been triggered previously. It will use the last screen name set.
Implementation recommendations
From a functional standpoint, we expect a screenview to be sent:
- When the screen appears
- When a modal/pop-up is closed and the user is back on the screen
- When the app is put in the foreground (after an app hide)
How to name screens
As a general rule, keep distinct screen names under 100. As they are used to map your app in Contentsquare, you will want something comprehensive.
Separate words with space, dash or underscore characters
If you want to generate screen names including more than one word, it is best to separate them and to do so using space, dash or underscore characters. Contentsquare handles automatically the formatting for them.
Example: For a sub-category list of a retail app, use Home & Living - Home Furnishings
instead of .homeLivingHomeFurnishings
Use screen template/layout names
As a general recommendation, use names referring to the screen template/layout rather than referring to the specific content (data). This will help:
- To keep the number of distinct screen names low and therefore make Contentsquare easier to use
- Remove the risk of sending Personal Data to Contentsquare
List of screen types falling into that category: Product detail, Event detail, Conversation/Chat, User profile...
Multiple layouts/states for one screen
In some cases, there will be screen that can have different layouts/states depending on the user context. In this situation, it would be interesting to append the layout/state value to the screen name. Examples:
- Home screen of a travel app adapting its layout on the user context:
State Screen name No trip planned Home - no trip
Trip planned Home - trip planned
Trip about to start Home - upcoming trip
Trip in progress Home - trip in progress
- Product detail screen of an e-commerce app with different layouts depending on the type of product:
State Screen name Default template Product detail
Template with suggested products Product detail - Suggestions
Template with bundled products Product detail - Bundle
Track Custom Variables
General principles
Usage
Custom variables are additional information on the page, the user or the session, sent within screenviews.
For example, they can include information on the current layout of a screen, like day/night mode.
Limits
On the server side
- It is possible to save up to 20 distinct custom variable per screenview. If more are received, only the first 20 custom variables, based on their
index
value, will be kept. - The
index
value of the custom variable is used to determine which custom variables to be kept. Onlyindex
value between 1 and 20 will be taken into account.
On the SDK side
- Every custom variable is composed of
index
,name
andvalue
. - If you are using the same
index
twice in the same screen, only the first (name
,value
) pair associated with theindex
will be kept. - It is possible to save up to 20 custom vars on the same screenview.
- In case
name
(max. 512 characters) orvalue
(max. 255 characters) maximum character length is reached, the SDK will automatically trim the exceeding characters. - If
name
orvalue
are empty, the SDK will instead send the literal string"cs-empty"
. - Use a consistent index for a given custom var within an application â for instance, if the "screen layout" is collected with an
index
of 3, use the slot 3 for this information on every screen of the application.
Defining custom variables
To define and send custom variables, you just need to use the following implementation:
import Contentsquare, { CustomVar } from "@contentsquare/react-native-bridge";
const cVar1: CustomVar = {
index: 1,
key: "CustomVarName1",
value: "CustomVarValue1",
};
const cVar2: CustomVar = {
index: 2,
key: "CustomVarName2",
value: "CustomVarValue2",
};
Contentsquare.send("ScreenName", [cVar1, cVar2]);
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 (number, mandatory)
- Currency (Currency or string, mandatory)
- Transaction ID (string, optional)
import Contentsquare, { Currency } from "@contentsquare/react-native-bridge";
// numeric currency: Contentsquare.sendTransaction(number, Currency, string?)
Contentsquare.sendTransaction(10, Currency.USD);
Contentsquare.sendTransaction(200, Currency.EUR, "my_transaction_1");
// alphanumeric currency: Contentsquare.sendTransactionWithStringCurrency(number, string, string?)
Contentsquare.sendTransaction(10, "USD");
Contentsquare.sendTransaction(200, "eur", "my_transaction_2");
Currency
The currency is conforming to the ISO 4217 standard. Although the currency can be passed either as "alphanumeric code" or "numeric code", you should always prefer using the bridge's Currency object values. If you have to pass the ISO code as a string, note that capitalization is not a factor (Currency.USD
, "USD"
, "Usd"
or "usd"
will all be treated as the US Dollar).
If the currency passed doesn't match our supported currencies, the SDK will send 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 screen view. If more are received, only the first 40 keys will be kept.
- If you are using the same key twice, 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. 512 characters) and value (max. 255 characters string or number of type Long between 0 and 232 - 1). In case these maximums length 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, you just need to use the following API. For each dynamic variable, we send:
- Key (string, mandatory)
- Value (string or integer, mandatory)
Note that if you send an integer as a value, it has indeed to be an integer. A null or a float will not be accepted as a valid parameter, and will result in an error.
Also, in order for you to be able to handle such errors happening when we try to send the dynamic variable (see the constraints on keys and values in the Limits section above), you can also add, as a last parameter, a function that we will call so you can handle it gracefully. Note that if you do not add that callback, we will simply log the error's message on the console whenever it happens.
import Contentsquare from "@contentsquare/react-native-bridge";
// alphanumeric value: Contentsquare.sendDynamicVar(string, string, (error) => {}?)
Contentsquare.sendDynamicVar("my key", "my value 1");
Contentsquare.sendDynamicVar("my key", "my value 2", ({ message }) => {
Toast.show(message, 0.3);
});
// numeric value: Contentsquare.sendDynamicVar(string, number, (error) => {}?)
Contentsquare.sendDynamicVar("my key", 10);
Contentsquare.sendDynamicVar("my key", 5000, (errorObject) => {
Console.log(errorObject.toString());
});
Type of the value â The value can be either a number
or a string
. For each case, available features won't be the same in the Contentsquare app:
- For number, you will be able to do some algebra. Example: sessions with dynamic variable key = "numberOfFriends" and value >= 10
- For string, auto-completion and Regular Expression will be available. Example: sessions with dynamic variable key = "accountType" and value is "Premium"
Sending a dynamic variable for each session
You may want to send a dynamic variable for each session (like the user's country or store). While triggering the dynamic variable at app launch will cover most cases, it will not be enough. A session can start when the app is put in foreground, after staying in background for more than 30 minutes. See Session definition section for more information.
That is why we also recommend sending such dynamic variable every time the app enters foreground.
You can use the AppState
API to detect foreground and trigger a dynamic variable.
Track WebViews
How it works
In order to be able to track what is happening in your WebViews, we need to be able to build a bridge between the content of the WebView and our native SDK. This implies two things:
1/ Implementing the Contentsquare Web Tracking Tag on all the web pages that are displayed in your app's WebViews and that you want to track.
đ Web Tracking Tag Documentation
Injecting a JavaScript bridge in your WebViews, which will allow the Tracking Tag you added to the web page in the previous step to communicate with our native SDK.
In order to inject this JavaScript, you will have to call two functions from our bridge:
function injectWebView(webViewTag: number): void;
function removeWebViewInjection(webViewTag: number): void;
The first one will inject your WebView with our JavaScript bridge, and the second remove the injection from it. The webViewTag
parameter is the target of your WebView object, which we will explain how to implement thereafter.
Implementing the JavaScript bridge
Here is a simple screen with a react-native-webview
WebView component. Let's detail how we will inject it with the Contentsquare JavaScript WebView interface.
import { WebView } from "react-native-webview";
const WebviewWithTagScreen = () => {
return (
<>
<WebView source={{ uri: "https://www.mywebpage.com" }} />
</>
);
};
export default WebviewWithTagScreen;
1. Retrieve the native tag to the WebView
In order to be able to call our bridge injection functions, you need to store the native tag of the WebView component, which acts as an identifier, so you can inject it with Contentsquare bridge later. We do that using the useState
hook (1), and setting it to the value of the webview target (2) we get from the onLoadStart
callback of the WebView component (3).
import React, { useState } from 'react';
import { WebView } from 'react-native-webview';
import { WebViewNavigationEvent } from 'react-native-webview/lib/WebViewTypes';
const WebviewWithTagScreen = () => {
const [webViewNativeTag, setWebviewNativeTag] = useState<number>(); // (1)
const loadStart = (event: WebViewNavigationEvent) => {
// react-native-webview typing for nativeEvent.target is not correct
// @ts-ignore
const webViewTag = (event.nativeEvent.target as number)
if (webViewTag) {
setWebviewNativeTag(webViewTag); // (2)
}
}
return (
<>
<WebView
source={{ uri: "https://www.mywebpage.com" }}
onLoadStart={loadStart} // (3)
/>
</>
);
};
export default WebviewWithTagScreen;
2. Call the Contentsquare bridge's injection/removal functions
In order for the injection and removal to be successful, you should call the bridge when your WebView is fully loaded, and before it is destroyed.
To avoid multiple injections issues, you have to create a new state (1) to set the tag once it is injected (2). You should inject the tag (3) in a function you pass to the onLoadEnd
callback of the WebView (4) and remove the injection in the useLayoutEffect
(5). Make sure to only inject it once, and pay attention to side effects of useLayoutEffect
when states change within your component.
import Contentsquare from '@contentsquare/react-native-bridge';
import React, { useState, useLayoutEffect } from 'react';
import { WebView } from 'react-native-webview';
import { WebViewNavigationEvent } from 'react-native-webview/lib/WebViewTypes';
const WebviewWithTagScreen = () => {
const [webViewNativeTag, setWebviewNativeTag] = useState<number>();
const [injectedWebViewTag, setInjectedWebViewTag] = useState<number>(); // (1)
const loadStart = (event: WebViewNavigationEvent) => {
// react-native-webview typing for nativeEvent.target is not correct
// @ts-ignore
const webViewTag = (event.nativeEvent.target as number)
if (webViewTag) {
setWebviewNativeTag(webViewTag);
}
}
const loadEnd = () => {
if (webViewNativeTag !== undefined && webViewNativeTag !== injectedWebViewTag) {
Contentsquare.injectWebView(webViewNativeTag); // (3)
setInjectedWebViewTag(webViewNativeTag); // (2)
}
}
useLayoutEffect(() => {
return () => {
if (webViewNativeTag !== undefined) {
Contentsquare.removeWebViewInjection(webViewNativeTag); // (5)
}
}
}, [webViewNativeTag])
return (
<>
<WebView
source={{ uri: "https://www.mywebpage.com" }}
onLoadStart={loadStart}
onLoadEnd={loadEnd} // (4)
/>
</>
);
};
export default WebviewWithTagScreen;
Session Replay
In order to implement Session Replay, go to React Native SDK Session Replay documentation.
Error Analysis đ
In order to implement Error Analysis, go to React Native SDK Error Analysis documentation.
Use Adobe Analytics
Analyze your data from anywhere in the customer journey using your Adobe Analytics segments.
Contentsquare allows you to use your Adobe Analytics segments in every Contentsquare feature (Journey Analysis, Page Comparator, Zoning Analysis, Session Replay).
Prerequisites
- Follow the instructions from Adobe Analytics for mobile apps
- Add the React Native AEP Analytics Extension to your project
Code implementation
Add the following code snippet in your application code. Add a call to the updateCsMatchingKey()
from within the index.js
file of your project root folder.
import { ACPCore } from "@adobe/react-native-acpcore";
import Contentsquare from "@contentsquare/react-native-bridge";
// TODO: Use local storage you prefer here
import AsyncStorage from "@react-native-community/async-storage";
export async function updateCsMatchingKey() {
const csMatchingKeyRecord = await AsyncStorage.getItem(
"csMatchingKey_creation_ts"
);
if (!csMatchingKeyRecord) {
await submitNewCsMatchingKey();
return;
}
const { timestamp } = JSON.parse(csMatchingKeyRecord);
if (Date.now() - timestamp > 30 * 60 * 1000) {
// if the key is not valid anymore, submit a new one
await submitNewCsMatchingKey();
}
// if the key is still valid, do nothing
}
async function submitNewCsMatchingKey() {
// Generate the matching key and store it in the local storage
const csMatchingKeyValue = `${Math.random()}_${Date.now()}`;
const newCsMatchingKeyRecord = {
csMatchingKey: csMatchingKeyValue,
timestamp: Date.now(),
};
await AsyncStorage.setItem(
"csMatchingKey_creation_ts",
JSON.stringify(newCsMatchingKeyRecord)
);
// Submit the matching key to Contentsquare and Adobe
Contentsquare.sendDynamicVar("csMatchingKey", csMatchingKeyValue);
ACPCore.trackState("csMatchingKey_state", {
csMatchingKey: csMatchingKeyValue,
});
}
Use Google Tag Manager
Prerequisite
If you are following this Google Tag Manager integration process, you should already have followed the React Native Firebase setup. We will assume that you are using the officially supported Firebase bridge the officially supported Firebase bridge. We will also assume that you have added the native GTM library to your iOS and Android project (following the iOS documentation and the Android documentation).
Before anything, you also need to integrate the Contentsquare Bridge (see section: Add Contentsquare to your app).
Integration
The whole integration will happen in the native part of your app, as well as in the GTM interface. Here is how it will work (note that you need to do these steps twice, once for iOS and once for Android):
- You will first setup custom tag, trigger and variables in your GTM interface.
- Then, you will have to add a custom Tag class in your native project.
- In your JavaScript/TypeScript code, or in your native code, you will use the Firebase Analytics library to send events, as explained thereafter.
- As you have created a trigger for that specific type of event, it will trigger the code in your native custom Tag class, where you will be calling the native SDK function corresponding to that event, thus allowing Contentsquare to collect those events.
Screenview events
Screenview events will be triggered in the Firebase React Native bridge by calling setCurrentScreen.
As the integration is exactly the same as the native ones, you can refer directly to the SDKs' explanation of the iOS integration and Android integration. You will have to do both in order to have a similar behavior across both platforms.
Transaction events
Transaction events will be triggered in the Firebase React Native bridge by calling logEcommercePurchase.
As the integration is exactly the same as the native ones, you can refer directly to the SDKs' explanation of the iOS integration and the Android integration. You will have to do both in order to have a similar behavior across both platforms.
Dynamic variable events
Dynamic variables are generally custom, and as such can be used with any type of event that can be boiled down to a key/value pair with value types that are valid for the Contentsquare SDK (a string or an unsigned integer). The most common event in that case will thus be a custom event, sent by calling logEvent
.
As the integration is exactly the same as the native ones, you can refer directly to the SDKs' explanation of the iOS integration/Android integration. You will have to do both in order to have a similar behavior across both platforms.
How the SDK works
Initialization
The way our SDK works is by auto-starting with the application launch and attaching to the current process in order to intercept the events and gestures we are interested in.
Configuration
Once started, our SDK fetches it config from our servers, and then depending on the segmentation size (defined by our team when you sign a contract) it will start collecting data from system and user events it detects from the runtime.
Tracking
The SDK monitors the application lifecycle events and the view hierarchy, and generates analytics data from the behavior of the app, the content of the screen and the interaction of the user. These events are then locally stored, and eventually sent to our servers in batches. We then aggregate that data to create usable visual information into our Web Application, which you use to gather insights.
Sending data
[tab] Android
Checkout the Native Android SDK documentation for Sending data
[tab] iOS
Checkout the Native iOS SDK documentation for Sending data
Session definition
A session represents a single period of user interaction in the app.
In Contentsquare, a session ends when the user has spent a certain amount of time outside the app. The SDK checks this when an app start
or app show
event is detected. This time spent outside the app, ending a session is set to 30 minutes by default. But it can be changed if it is requested.
If the app is put in the background or killed (intentionally by the user or by the OS) but the user comes back within 30 minutes, it will not end the session. These events are considered to be part of a session.
Collected data points
- The events are in JSON format, which lists the properties and their description in comment.
- Events are sent to the server in batches.
- A batch is a subset of events originating from one session. A session can send events in more than one batch.
- The batch size is defined in a run configuration file specific to each app (50 events by default).
Requests meta data
Each batch has a common header, a set of device specific, and repeatable information and an array of events, which is immutable. The header is composed at the moment of sending, so it has to be constant info ONLY. The array in the payload is data stored at the moment of collection.
The structure of the batches of events will have the following format:
{
pid:8, // int - ProjectId - represented in the mobile config format
uid:"ac1529a7-59f6-49d9-b254-6f0a22f57284", // String - uuid Unique user ID
dt:4, // int - device type (loosely enforced enum - [SDK-phone : 4, SDK-tablet :5])
dma:"Samsung", // String - device manufacturer. This property is optional and if by any chance the device model cannot be determined it will be dropped from the Json object.
dmo:"SG", // String - device model. This property is optional and if by any chance the device model cannot be determined it will be dropped from the Json object.
os:"7.0", // String - os version (Android version name 6.0, 7.0, 8.0)
l:"en_US", // String - Language in iso-639 format https://www.ibabbleon.com/iOS-Language-Codes-ISO-639.html
tz:"Europe/Paris", // String - timezone https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
now:1522159618000, // long - timestamp when the batch was sent
to:{ // object - type origin of the event
an:"appname" // String - application name
st:"SDK-android", // String - type of SDK
sf:"release", // string - SDK flavor/variant [release/debug/god]
},
r:{ // Device - resolution.
w:1080, // int - width
h:1920 // int - height
d: 1.5 // The device density as float. Its values can vary between (0.75 and 10)
},
pl:[] // JSon array payload - list of event objects, see below
}
Events
Events meta data
All events have a common first part (don't confuse it with the header explained above). This common section is data which is common for all events by type but is gathered at the moment the event occurred. This common section is a part of the actual event payload.
{
upt:1522, // long - system update in milliseconds
euid:"euid", // String - event UUID
url:"app-and://identifier/mainPath/secondaryPath?title=screeName", // String - screenName is passed in the title query Parameter
scn:4, // int - the number of screens already shown in the session
c:3, // int - connectivity type [-1 - offline, 0 - error, 1 - wifi, 2 - 2g, 3 - 3g, 4 - 4g]
ci:"verizon", // String - carrier_id when user is on mobile network
o:1, // int - orientation [0 = portrait, 1 = landscape]
vo:{ // object - version origin of the event
sv:"2.1", // string version of the SDK
sb:4, // int - SDK build number
av:"appVersion", // String - application version
af:"appFlavor" // String - application string - [release/debug/god]
ab:1 // int - application build number
},
sn:1, // int - session id (positive int)
t:12894726459435 // long - timestamp of the event (in milliseconds)
}
All event specific properties are appended to this JSON object.
App Start
This event describes the absolute start of the app.
The trigger for this event is the absolute start of the app.
This is the first event sent when the SDK is invoked.
ea: 0; // int - event action - defined above
App Show
This event is sent when the user brings the app in the foreground (switching from another app, exiting lock screen, etc.). This event means the app is focused.
ea: 1; // int - event action - defined above
App Hide
This event is sent when the user exit (minimizes) the app, or switches to something else . This event means the app is not focused and the session might end, but we have not completely ended the session yet, as the user might return.
ea: 2; // int - event action - defined above
Screenview
Everything starts with a View event. This is an event which describes the equivalent of a "page view" in the web. This event is sent when the Track Screen API is called.
ea:4 // int - event action - defined above
st:"title", // String - screen title
sl:34543 // int - (load time) screen load time (diff between last action and this event)
Tap
Single Finger gesture event, when the user is interacting with a loaded screen. This is an event which describes the equivalent of a "click" in the web. This event is defined by the following sequence of touch events:
- Touch Down -> N x Touch Move -> Touch Up
ea:6 // int - event action - defined above
tvp:"[root]>view#id>view2>", // String - target view path
tvid:"btn_ok", // String - target view id
ur: true, // boolean - was this a "responsive" touch event (the target view had a handler)
Long press
Single Finger gesture event, when the user is interacting with a loaded screen.
This event is defined by the following sequence of touch events:
- Touch Down â N x Touch Move â Touch Up
- Duration: > 500ms
- Distance: < 24 dp
ea:8 // int - event action - defined above
tvp:"[root]>view#id>view2>", // String - target view path
tvid:"btn_ok", // String - target view id
Drag (Slow Swipe)
Single Finger gesture event, when the user is interacting with a loaded screen.
This event is defined by the following sequence of touch events:
- Touch Down â N x Touch Move â Touch Up
- Distance: > 48 dp
- Finger Velocity < 100 dp/s
ea:9 // int - event action - defined above
tvp:"[root]>view#id>view2>", // String - target view path
tvid:"btn_ok", // String - target view id
fd: 3, // int - finger direction - [1,2,3,4,5] -> [up, down, left, right, complex_pattern]
tvd:100, // int - target view distance dragged
tvv:100 // int - target view velocity while dragging dp/s
Flick (Fast Swipe)
Single Finger gesture event, when the user is interacting with a loaded screen.
This event is defined by the following sequence of touch events:
- Touch Down â N x Touch Move â Touch Up
- Distance: > 48 dp
- Finger Velocity > 100 dp/s
ea:10 // int - event action - defined above
tvp:"[root]>view#id>view2>", // String - target view graph path
tvid:"btn_ok", // String - target view id
fd: 3, // int - finger direction - [1,2,3,4,5] -> [up, down, left, right, complex_pattern]
tvd:100, // int - target view distance scrolled
tvv:100 // int - target view velocity while scrolling dp/s
Transaction
To track transactions, we provide a public API which can send a transaction object (see section Track Transactions). This object must contain the following parameters:
ea:16, // int - event action - defined above
tr:{ // a json object with different properties defining the transaction made
vl: 20.0, // mandatory - float - the value of the transaction
cu: 978, // mandatory - int - the ISO 4217 code of the currency of the transaction
id: "32akjkljklJ575775" // optional - string - an id for the transaction
}
Dynamic variables
To track dynamic variables we provide a public API (see section Dynamic variables).
// Dynamic variable event with a string value
ea:18, // int - event action - defined above
k:"key", // String - Custom key assigned by client.
v:"value" // String - Custom value assign by client.
// Dynamic variable event with a number value
ea:19, // int - event action - defined above
k:"key", // String - Custom key assigned by client.
v: 2344 // Integer - Custom value assign by client.
Reliable targets (iOS only)
The identifier associated with each view in your app is the concatenation of the list of its ancestors in the React Native tree view.
This means that if you have the following component:
const basicComponent = () => {
return (
<View>
<Text>Hello world!</Text>
<TextInput placeholder="Enter your name" />
</View>
);
};
You may always want to use the same id for this component, even if you publish a new version of the app in which it has been moved in the tree view.
Having a reliable target for a view or a container of views enables the analysis of data across various Snapshots from different dates and versions, including layouts or different A/B testing variations.
Here are examples of how the reliable targets feature can be used :
- Tracking elements that can dynamically move on a page (e.g., Customizable profile page).
- Tracking elements that you want to monitor from one version to another, even if their position changes (e.g., Moving carousel position from top to bottom).
- Tracking elements during A/B testing (e.g., Testing new and old Product page on the same version).
- Tracking elements that can be used on multiple pages (e.g., Search bar).
- Ensuring that a call to action has a unique identifier wherever it appears on a screen (e.g., AddtoCart button).
The Contentsquare React Native SDK provides a CSReliableTarget
component that can be used to wrap the component you want to track reliably.
CSReliableTarget
accepts a mandatory name
prop that allows the identification of the component to track.
const componentWithReliableTarget = () => {
return (
<CSReliableTarget name="MyComponentTracked">
<View>
<Text>Hello world!</Text>
<TextInput placeholder="Enter your name" />
</View>
<CSReliableTarget>
);
};
Security
Transmission and hosting
Our server side uses HTTPS to makes sure that data is encrypted in transport.
Our hosting solution is a PCI DSS Level 1 Service Provider.
What is not collected
- Passwords from password fields
- Geo location information
- Information from contacts, emails, or any other user identifiable information.
- Text from labels, buttons, and any other widget which contains text
- Accessibility information from any widget which the user interacts with
- Labels printed on the screen of any kind.
Compatibility
Each version of the Contentsquare bridge will be linked to specific, fixed versions of each native SDK. In order to make that clear, here is a compatibility table to consider when choosing your version of the bridge (refer to the React Native Bridge Changelog to know what the changes are for each version.
Bridge Version | iOS SDK Version | Android SDK Version | Min React Native Version | Max React Native Version |
---|---|---|---|---|
3.7.0 | 4.25.1 | 4.21.0 | 0.65.0 | 0.72.x |
3.6.1 | 4.24.0 | 4.20.0 | 0.65.0 | 0.72.x |
3.6.0 | 4.24.0 | 4.20.0 | 0.65.0 | 0.72.x |
3.5.0 | 4.23.0 | 4.19.0 | 0.65.0 | 0.71.x |
3.4.1 | 4.22.1 | 4.18.1 | 0.65.0 | 0.71.x |
3.4.0 | 4.22.1 | 4.18.1 | 0.65.0 | 0.71.x |
3.3.1 | 4.20.0 | 4.15.0 | 0.65.0 | 0.71.x |
3.3.0 | 4.20.0 | 4.15.0 | 0.65.0 | 0.71.x |
3.2.0 | 4.20.0 | 4.15.0 | 0.65.0 | 0.71.x |
3.1.0 | 4.18.0 | 4.15.0 | 0.65.0 | 0.70.x |
3.0.0 | 4.17.0 | 4.14.0 | 0.65.0 | 0.70.x |
2.8.0 | 4.16.0 | 4.14.0 | 0.59.0 | 0.68.x |
2.7.0 | 4.15.1 | 4.11.0 | 0.59.0 | 0.68.x |
2.6.0 | 4.13.0 | 4.9.0 | 0.59.0 | 0.68.x |
2.5.3 | 4.10.1 | 4.7.0 | 0.59.0 | 0.67.x |
2.5.2 | 4.10.1 | 4.7.0 | 0.60.0 | 0.66.x |
2.5.1 | 4.10.1 | 4.7.0 | 0.60.0 | 0.66.x |
2.5.0 | 4.10.0 | 4.6.0 | 0.60.0 | 0.66.x |
2.4.0 | 4.9.0 | 4.4.0 | 0.60.0 | 0.64.x |
2.3.0 | 4.6.0 | 4.3.0 | 0.60.0 | 0.64.x |
2.2.1 | 4.4.0 | 4.2.0 | 0.60.0 | 0.64.x |
2.1.0 | 4.1.0 | 4.1.0 | 0.60.0 | 0.63.x |
2.0.0 | 4.0.0 | 4.0.0 | 0.60.0 | 0.63.x |
1.1.1 | 3.2.1 | 3.2.0 | 0.60.0 | 0.63.x |
1.1.0 | 3.2.0 | 3.2.0 | 0.60.0 | 0.63.x |
1.0.0 | 3.1.1 | 3.1.0 | 0.60.0 | 0.62.x |
Known limitations and recommendations
Use of PanResponder
If you are using PanResponders in your app, a bug might appear on the element implementing it where it will only move for about a second and then freeze. This bug is caused by a conflict between the React Native SDK and our Bridge related to tracking swipe events. May you encounter this bug, the current workaround is to stop the Contentsquare tracking when the pan gesture starts, and resume it as the gesture ends, as follows:
const panResponder = useRef(
PanResponder.create({
[...]
onPanResponderGrant: (evt, gestureState) => {
Contentsquare.stopTracking();
[...]
},
onPanResponderRelease: (evt, gestureState) => {
Contentsquare.resumeTracking();
[...]
},
[...]
})
).current;
Note that, although this workaround fixes the bug, applying it means that swipes on view using the PanResponder won't be tracked by Contentsquare.
Impact on performances
We always strive to be non-intrusive, and transparent to the developers of the client app.
We apply this rule on the performance as well.
Troubleshooting
Requests are failing
In order for Contentsquare to work, you need to make sure the following endpoints are not blocked by your network (VPN):
Request | Endpoint | Detail |
---|---|---|
Config file | https://mobile-production.content-square.net | See Configuration |
Analytics data (EU) | https://m.csqtrk.net | See Sending data |
Analytics data (US) | https://m-aus1.contentsquare.net | See Sending data |
Session Replay data (EU) | https://ka-aeu1.contentsquare.net | See Session Replay requests |
Session Replay data (US) | https://ka-aus1.contentsquare.net | See Session Replay requests |
Snapshot (EU) | https://s.contentsquare.net | See Snapshot capture |
Snapshot (US) | https://s-aus1.contentsquare.net | See Snapshot capture |
Changelog
đ React Native SDK Changelog
Related Links
đ Mobile SDK Homepage
đ Android SDK Documentation
đ WebView Tracking Tag Documentation