React Native Plugin

The OneTrust Native SDK is natively written for Apple and Android platforms. Through the use of bridging headers, the native Java and Swift functions can be exposed to your React Native application.

The OneTrust React Native bridging library is available in the NPM.js repository.

Initialization

The OneTrust SDK retrieves an object that contains all the data needed to present a UI to a User to collect consent for the SDKs used in your application. The data returned is determined by the configurations made in the OneTrust Admin console.

startSDK

This method is the initialization method for the SDK. It makes between 1-2 network calls, depending if an IAB2 template is fetched or not.

OTPublishersNativeSDK.startSDK(
  'storageLocation',
  'domainIdentifier',
  'languageCode',
  {countryCode: 'us', regionCode:'ca'},
  true,
)
  .then((responseObject) => {
    console.info(`Download status is ${responseObject.status}.`);
    // get full JSON object from responseObject.responseString
  })
  .catch((error) => {
    console.error(`OneTrust download failed with error ${error}`);
  });

Arguments

ArgumentTypeDescription
storageLocationStringThe CDN location for OneTrust to pull
domainIdentifierStringThe App ID to load
languageCodeStringThe ISO language code to load the data
paramsDictionaryDictionary of parameters to override initialization settings. Parameters are optional, but you must have an non-null object defined, even if it is blank. (See below)
autoShowBannerBooleanAutomatically display the banner when download has completed successfully. This follows the shouldShowBanner() logic to ensure the user should be presented with a banner. autoShowBanner defaults to false.

If autoShowBanner is set to true and shouldShowBanner() logic returns true, the method for showBannerUI() will be called automatically and the user will see the Banner UI. You will not need to separately call showBannerUI() as this is taken care of by the autoShowBanner logic.

What should the storageLocation value be?

The required storageLocation value differes based on your OneTrust tenant environment. The table below will help identify the correct value.

EnvironmentStorage Location
cookieprocookie-cdn.cookiepro.com
app-ukcdn-ukwest.onetrust.com
app-aucdn-au.onetrust.com
app-apaccdn-apac.onetrust.com
appcdn.cookielaw.org
app-decdn.cookielaw.org
app-eucdn.cookielaw.org
freecdn.cookielaw.org
iappcdn.cookielaw.org
iapp-eucdn.cookielaw.org
trialcdn.cookielaw.org
uatcdn.cookielaw.org
uat-decdn.cookielaw.org

What should the domainIdentifier be?

The required domainIdentifier value can be retrieved from the OneTrust Admin UI. Please contact your Project Manager or OneTrust consultant for help locating this value.

Params

All of the values are optional and are expected to be Strings.

KeyValueDescription
countryCodeISO country codeOverrides the geolocation of the user
regionCodeISO region codeOverrides the geolocation of the user, used in conjunction with countryCode
profileSyncParamsDictionarySee Below - Dictionary containing the parameters to sync consent stored in OneTrust against an identifier

Capture Records of Consent

When a user gives consent, the SDK automatically saves the consent profile locally to disk. This is so a User's settings can be reflected in the Preference Center UI without having to make a network call.

Optionally, a user's consent can be saved to OneTrust servers, this feature is known as Capture Records of Consent and is enabled in the Geolocation Rules section of OneTrust Admin, not on the SDK locally.

Enabling Capture Records of Consent is the only way to feed OneTrust Reports and Dashboards, otherwise the consent data is only kept locally on the device.

Cross Device Consent

Cross Device Consent is an optional feature. These parameters are not required for initializing the SDK to fetch and display Banners and Preference Centers to users. The object contains two key/value pairs, as demonstrated below. More information about the requirements for the JWT that is passed as syncProfileAuth can be found in the Cross-Device Consent My.OneTrust article.

const syncParams = {
  identifier: 'bnbTest',
  syncProfileAuth: 'myJWT',
};
KeyTypeDescription
identifierStringUser identifier
syncProfileAuthStringJWT representing the authorization to retrieve the consent profile.

Display User Interfaces

The OneTrust SDK manages several different user interfaces to display to a User. Before showing how to display them, please review the list of interfaces below.

NameDescriptionMethod to Show
BannerNotice to the user of their privacy rights. Has configurable text and buttons for Accept All, Reject All, Manage Preferences, and Close Banner.

Note: Each of these buttons can be toggled On/Off in the Admin Console.
showBannerUI()
Preference CenterAn interface for the user to view their current profile settings and update their choices based on the configuration provided for them. Has configurable text and buttons for Accept All, Reject All, Save Settings, and Close Preference Center.

Note: You can choose to hide each button except Save Settings - this is required for a User to update their choices.
showPreferenceCenterUI()
Purpose DetailsThe Purpose Details (or Category Details) view shows granular detail about the category and also shows the SDK LIst link, Vendor List link, and child categories based on configuration.-
SDK ListAn interface to show a granular list of SDKs to the user. This list may be filtered by Category to provide more transparency to the User.

Note: This can hidden in Template Settings in the Admin Console.
-
IAB Vendor ListAn interface, shown only for IAB2 type templates, displays a list of 3rd party ad tech vendors under management by the application. This provides a way for users to opt in/out of consent for a particular vendor.-
Vendor DetailsA child interface of Vendor List, this view shows more granular information about a vendor and its Purpose, Legitimate Interest, Special Feature, and Special Purpose settings.-

The user interfaces without methods indicate they can only be navigated to based on User navigation and Admin Portal settings.

showBannerUI

This method will always show the Banner UI, regardless of shouldShowBanner value.

OTPublishersNativeSDK.showBannerUI()

showPreferenceCenterUI

This method will always show the Preference Center UI, regardless of shouldShowBanner value.## shouldShowBanner

This method determines if the OneTrust Banner needs to be presented to the user or not. The logic tree for computing this value is:

  1. Is the showAlertNotice property in the JSON set to true?

    • If no, the method returns false because a banner is not meant to be shown for this region.
    • If yes, move to the next check.
  2. Has the User given/updated their consent before?

    • If no, the method returns true and a banner should be shown to the user
    • If yes, move to the next check.
  3. Did the most recent Publish from OneTrust ask User to re-consent?

    • If yes, the method returns true because the User is being asked to re-consent.
    • If no, the method returns false because the User has already given prior consent and is not being asked to re-consent.

Note: If you are using OneTrust's pre-built UI, it is likely you won't need to call this method, but good to know how it works as it is decides the outcome of setupUI method.

OTPublishersNativeSDK.shouldShowBanner().then((result) =>
  console.log('Should the banner be shown? ', result),

Customize User Interfaces In-App

OneTrust supports the customization of UI Elements from within the application's code, using a .plist file on iOS and a .json file on Android. Specifics of what can be controlled and the prerequisites for setup are detailed in the iOS and Android native documentation sections.

Android - Custom styling with UXParams JSON

OneTrust allows you to add custom styling to your preference center by passing in style JSON in a certain format. Build out your JSON by following the guide in the OneTrust Developer Portal.

Simply pass in the JSON as a string as a parameter in the initialization.

const uxParamsJSON = JSON.stringify(require('./assets/AndroidUXParams.json'));

OTPublishersNativeSDK.startSDK(
  'cdn.cookielaw.org',
  '162cfe19-aff6-4d60-b10e-6e7b6fdcfb8b-test',
  'th',
  {androidUXParams: uxParamsJSON},
  true,
)

iOS - Custom Styling with UXParams Plist

Custom styling can be added to your iOS React Native application by using a .plist file in the iOS platform code. In addition to adding the .plist file (which can be obtained from the OneTrust Demo Application) to your bundle, there are a few changes that need to be made in the platform code, outlined below. Review the guide in the OneTrust Developer Portal.

In appDelegate.h, import OTPublishersHeadlessSDK and make sure that AppDelegate conforms to the OTUIConfigurator protocol.

#import <React/RCTBridgeDelegate.h>
#import <UIKit/UIKit.h>
#import <OTPublishersHeadlessSDK/OTPublishersHeadlessSDK.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate, RCTBridgeDelegate, OTUIConfigurator>


@end

In appDelegate.m, set the UIConfigurator to self. Then conform to the shouldUseCustomUIConfig and customUIConfigFilePath protocol methods.


#import "AppDelegate.h"
#import "MainViewController.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
    [OTPublishersHeadlessSDK.shared setUiConfigurator:self]; //set UIConfigurator to Self
    ...
    return ...
}


- (BOOL)shouldUseCustomUIConfig { //conform to shouldUseCustomUIConfig
    return true;
}

- (NSString *)customUIConfigFilePath{ //conform to filepath protocol method
    NSString * configFile = [[NSBundle mainBundle] pathForResource:@"OTSDK-UIConfig-iOS" ofType:@"plist"]; //find path for config file
    return configFile;
}

@end

When Consent Changes

When a User updates their consent choices or interacts with a OT SDK UI, the Application needs to become aware of that so it can control the next set of actions like:

  • Allowing or Restricting processing of 3rd party SDKs based on their categorization
  • Passing latest User consent values to 3rd Party SDKs
  • Passing the IAB’s encoded TC String to 3rd party SDKs
  • Passing the IAB’s USP String to 3rd Party SDKs
  • Routing the User to another location in the App
  • Displaying messages to the User of their changes
  • Logging updates to internally owned APIs
  • etc.

Two Ways to Get Consent Values

  • Query for Consent
  • Listen to events

Consent Values

OneTrust universally uses the following values for consent status:
|Status|Explanation|
|-|-|
|1| Consent is given (An end user interacts with the SDK and gives consent.)|
|0|Consent is not given (An end user interacts and does not give consent.)|
|-1| Consent has not been collected (The SDK is not yet initialized for the end user.)|

Querying for Consent of a Category

To obtain the current consent status, use the getConsentStatusForCategory() method, which returns an Int:

OTPublishersNativeSDK.getConsentStatusForCategory('C0002').then((result) =>
  console.log('Consent Status for category C0002 = ' + result),
);

Querying for Consent for a SDK ID

To obtain the current consent status, use the getConsentStatusForSDKID() method, which returns an Int:

OTPublishersNativeSDK.getConsentStatusForSDKID('06a13b51-81a1-42a6-9121-80b4fc52d859').then((result) => 
  console.log('Consent Status for 06a13b51-81a1-42a6-9121-80b4fc52d859 = ' + result), 
);

Listening for Consent Changes

The OneTrust SDK emits events as consent statuses change.

On iOS, you must tell the bridge which consent categories and SDK IDs are eligible for broadcast. The code sample below shows an application allowing broadcasts for two categories (CXXXX) and an SDK ID (as a GUID).

  OTPublishersNativeSDK.setBroadcastAllowedValues(['C0002','C0003']);

The parameters passed are what events the iOS platform will be allowed to emit. This method has a conditional built in so that it will not execute on Android devices.

To start listening for consent changes, call the listenForConsentChanges method, which accepts a Category ID or an SDK ID as a string, and a callback function.

OTPublishersNativeSDK.listenForConsentChanges('C0002', (id, status) =>
  console.log('Consent status for ', id, ' has been updated to ', status),
);

The callback will be executed every time the consent status is updated.

To stop listening for changes (for example, when your component is unmounted,) simply call

OTPublishersNativeSDK.stopListeningForConsentChanges();

This will cancel all listeners.

Passing Consent to WebView

If your application uses WebViews to present content and the pages rendered are running the OneTrust Cookies CMP, you can inject a JavaScript variable, provided by OneTrust, to pass consent from the native application to your WebView.

The JavaScript must be evaluated before the Cookies CMP loads in the webview, therefore, it is recommended to evaluate the JavaScript early on in the WebView load cycle:

var jsToPass = await OTPublishersNativeSDK.getOTConsentJSForWebView()  
//WebView JS Evaluation logic here

If your application is using react-native-webview, any injected JavaScript is wrapped in a self-invoking function, meaning that any variables set are not in the global scope. For the OneTrust Cookie Compliance module to pick up the required changes, the variable must be at a global scope. To accomplish this, a substring can be used to place the payload in the window scope:

var jsToPass = await OTPublishersNativeSDK.getOTConsentJSForWebview()  
jsToPass = `window.OTExternalConsent${jsToPass.substring(21)}`  
//WebView JS Evaluation logic here

Apple's App Tracking Transparency Requirements

With the release of iOS / iPadOS / tvOS 14, Apple requires applications to provide more transparency to users for the the data the application and the application's third-parties are accessing from the user.

New Apple Requirements:

Note: Watch this technical implementation recording on myOneTrust to help you measure and report on the impact of the iOS 14 App Tracking Transparency IDFA prompt.

Displaying a Pre/Post-Prompt

App Tracking Transparency

If enabled in your template, OneTrust can render a pre-prompt and then show the App Tracking Transparency prompt immediately after. OneTrust also exposes a method to access the status of the user's App Tracking Transparency selection.

To surface the pre-prompt:

//be sure to import {OTDevicePermission} from 'react-native-onetrust-cmp'

OTPublishersNativeSDK.showConsentUI(OTDevicePermission.IDFA).then(()=>{
  console.log("ATT Prompt Complete")
})

To get the status of the user's ATT selection:

var status = await OTPublishersNativeSDK.getATTStatus()
console.log(`ATT Status is ${status}`)

Status will return 'authorized', 'denied', 'notDetermined', or 'restricted'. The definitions of each are consistent with Apple's definitions.

FAQs

Can the OneTrust SDK change the consent value for the App Tracking Transparency permission?

No, Apple does not allow this. The App Tracking Transparency permission can only be updated in the following ways:

  • User interacts with Apple's App Tracking Transparency permission prompt
  • User updates the App Tracking Transparency permission value in the device's settings

The OneTrust SDK can only:

  • Show Apple's App Tracking Transparency permission prompt to the user, via Pre-Prompt
  • Deep link the user to the application's device settings for updating App Tracking Transparency permission, via Post-Prompt

What happens when the user closes the app or turns off their device while the App Tracking Transparency permission prompt is being displayed?

Apple records this as a Ask App Not to Track user selection. This will impact the application in the following ways:

  • The application will not be allowed to show the App Tracking Transparency permission prompt to the user again, since it was already shown once.
  • Calling OneTrust SDK's showConsentUI() method will result in a Post-Prompt, not a Pre-Prompt.
  • If Consent Logging feature is enabled, the next time startSDK() or checkAndLogConsent() is called, the OneTrust SDK will log a consent transaction for the App Tracking & Transparency purpose with status Opted Out.

What happens when the user closes the app or turns off their device while the OneTrust SDK's Pre-Prompt is being shown?

Nothing really happens:

  • The OneTrust SDK won't log any consent transactions
  • The next time OneTrust SDK's showConsentUI() method is called, the Pre-Prompt will still be shown because the App Tracking Transparency permission prompt has yet to be shown to the user.

What happens if the user updates the App Tracking Transparency toggle in device settings to a new value and returns to the application?​

The application will restart (Apple device does this automatically).

If Consent Logging is enabled on Geolocation rule, the next time startSDK() is called, the OneTrust SDK will log a consent transaction for ​App Tracking & Transparency​​ purpose with status of Confirmed or Opted Out (depending on user’s new selection)

Universal Consent Purposes

Universal consent allows your application to collect consent for off-device processing. For example, your application might need to request permission to send a user promotional SMS messages. In OneTrust, after a Universal Consent transaction is committed, integration workflows can be triggered in the OneTrust tool.

Universal Consent requires a user identifier to work properly. In order to set a data subject and keep their consent in sync with other collection methods, utilize the Profile Sync Params guidance.

Display Universal Consent Preference Center

To load the Universal Consent preference center over the current screen, simply call

OTPublishersNativeSDK.showConsentPurposesUI()

Query for Universal Consent Values

This plugin exposes async methods to retrieve the current state of the users' consent.

StatusExplanation
1Consent is given (An end user interacts with the SDK and gives consent.)
0Consent is not given (An end user interacts and does not give consent.)
-1Consent has not been collected (The SDK is not yet initialized for the end user.)

To query for the top-level purpose's consent:

var consent = await OTPublishersNativeSDK.getUCPurposeConsent('purposeId')
ArgumentTypeDescription
purposeIdStringThe GUID of the purpose to retrieve.

To query for a custom preference nested under a purpose:

var consent = await OTPublishersNativeSDK.getUCCustomPreferenceConsent('customPreferenceOptionId',
 'customPreferenceId','purposeId')
ArgumentTypeDescription
customPreferenceOptionIdStringThe GUID of the custom preference option
customPreferenceIdStringThe GUID of the custom preference group
purposeIdStringThe GUID of the purpose under which the custom preference is nested.

To query for a topic nested under a purpose:

var consent = await OTPublishersNativeSDK.getUCTopicConsent('topicOptionId', 'purposeId')
ArgumentTypeDescription
topicOptionIdStringThe GUID of the topic option
purposeIdStringThe GUID of the purpose under which the custom preference is nested.

Programatically Set Universal Consent Values

The package exposes methods to programatically set the users' consent values. A common use case is when a sign-up form has a checkbox at the bottom to allow the user to opt into emails. In this case, the application would set the value of the associated purpose, and the user could change his or her decision later in the preference center.

After making consent updates, the application must call the saveUCConsent() function to commit the changes.

To update the top-level purpose's consent:

var consent = await OTPublishersNativeSDK.updateUCPurposeConsent('purposeId', true)
ArgumentTypeDescription
purposeIdStringThe GUID of the purpose to update
consentBooleanWhether or not consent has been granted for the specified item

To update a custom preference nested under a purpose:

var consent = await OTPublishersNativeSDK.updateUCCustomPreferenceConsent('customPreferenceOptionId',
 'customPreferenceId','purposeId', true)
ArgumentTypeDescription
customPreferenceOptionIdStringThe GUID of the custom preference option
customPreferenceIdStringThe GUID of the custom preference group
purposeIdStringThe GUID of the purpose under which the custom preference is nested.
consentBooleanWhether or not consent has been granted for the specified item

To update a topic nested under a purpose:

var consent = await OTPublishersNativeSDK.updateUCTopicConsent('topicOptionId', 'purposeId', true)
ArgumentTypeDescription
topicOptionIdStringThe GUID of the topic option
purposeIdStringThe GUID of the purpose under which the custom preference is nested.
consentBooleanWhether or not consent has been granted for the specified item

Save Consent

After making updates to the consent values, the application must call the following method to commit the changes:

  OTPublishersNativeSDK.saveUCConsent()