Cordova / Ionic

The OneTrust Cordova / Ionic library is hosted on NPM.

Versioning and Installation

Versioning

The SDK version used in the app must match the version of the app data published from your OneTrust tenant. For example, if you've published version 202408.1.0 of the app data in your OneTrust environment, you must use npm package version 202408.1.0 as well. It is recommended to specify a version to avoid automatic updates, as a OneTrust publish is typically required when you update your SDK version.

Installation

To install the OneTrust Cordova/Ionic plugin, use the following command

//Cordova
cordova plugin add [email protected]

//Ionic
ionic cordova plugin add [email protected]

Uninstallation

To uninstall, run the following in your project folder

cordova plugin remove cordova-plugin-onetrust-cmp

Android Requirements

For Android implementations, the AndroidX dependency is required. Add the following to your config.xmlfile, inside of your Android platform tag.

<preference name="AndroidXEnabled" value="true" />

Implementation and Development

The following sections are laid in a typical order of development and UX.

Initializing the SDK

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.

Before proceeding, make sure that your SDK Data has been published inside of the OneTrust Admin Portal. If the data has not been published, the SDK will not have any data to retrieve. View instructions on how to publish here.

Import OneTrust

OneTrust methods can be accessed via window.OneTrust or cordova.plugins.OneTrust.

startSDK

This method is the initialization method for the SDK. It makes between 1-2 network calls:

  • 1 network call when using a non-IAB TCF template
  • 2 networks calls when using a IAB TCF template
window.OneTrust.startSDK(storageLocation, domainIdentifer,languageCode, params,(status) => {
    console.log("SDK Downloaded Successfully!")
},(error) =>{
  console.log("SDK Failed to initialize! Error = "+error)  
})
ArgumentTypeDescriptionRequired
storageLocationStringThe CDN location for the JSON that the SDK fetches. (Usually, but not always, cdn.cookielaw.org.)Yes
domainIdentifierStringThe App ID to load from the OneTrust Admin ConsoleYes
languageCodeString2-digit or 4-digit (in the case of advanced languages) ISO language code used to return content in a specific language.

Note: Any language code format which is not listed in OneTrust environment will be considered as invalid input.

Note: If the languageCode passed by your application is valid, but does not match with a language configuration for your template, then the SDK will return content in the default language configured in OneTrust environment (usually, but not always, English).
Yes
paramsJSON ObjectDictionary of parameters to override initialization settings. Parameters are optional, but you must have a non-null object defined, even if it is blank. See params section below for more information. No, nullable
successfunctionSuccess handler once download has completedNo
failurefunctionFailure handler if download failsNo

Params

The values below can be placed in a JSON object and passed in the params argument of startSDK to provide additional configuration.

Example

const params = {
    syncParams: {
      identifier: '[email protected]',
      syncProfileAuth:'eyJhb...',
    },
    countryCode:"US",
    regionCode: "CA",
    androidUXParams: uxJson
  }

All values below are optional.

KeyValueDescription
countryCodeISO country codeOverrides the geolocation of the user
regionCodeISO region codeOverrides the geolocation of the user, used in conjunction with countryCode
androidUXParamsJSON ObjectSets UI/UX overrides for Android (see Custom Styling section below)
syncParamsJSON ObjectAllows for cross-device syncing of consent preferences. See Cross-Device Consent below.

Cross Device Consent

Cross Device Consent is an optional feature. The parameters below are not required for initializing the SDK. Each of the parameters are required to sync the user's consent profile.

KeyTypeDescription
identifierStringUser identifier associated with the user for setting or retrieving consent
syncProfileAuthStringJWT auth token required to retrieve a user profile

Display User Interfaces

The OneTrust SDK manages several different user interfaces to display to a user. Here's a list below for your reference:

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.
window.OneTrust.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.
`window.OneTrust.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.none, sub-view of Preference Center
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 be hidden in Template Settings in the Admin Console.
none, sub-view of Preference Center
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.none, sub-view of Preference Center
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.none, sub-view of Preference Cente

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 the shouldShowBanner value

window.OneTrust.showBannerUI()

showPreferenceCenterUI

This method will always show the Preference Center UI.

window.OneTrust.showPreferenceCenterUI()

shouldShowBanner

This method determines if a Banner UI should be displayed based on SDK determined logic.

window.OneTrust.shouldShowBanner((result)=>{
    console.log("A banner should be shown = "+result)
})

Example of how to combine initialization success handler with the shouldShowBanner function to automatically show a banner, if required, once the SDK download has completed:

window.OneTrust.startSDK(storageLocation,domainId,langCode, params, (status) =>{
        window.OneTrust.shouldShowBanner((shouldShow) => {
            if(shouldShow){
                window.OneTrust.showBannerUI()
            }
        })
    }, (error) =>{
        console.log(error)
    })

How is shouldShowBanner() computed?

  1. Is the geolocation rule configured to show a banner? This is controlled by the showAlertNotice property in the JSON being true.

    • If showAlertNotice = false, the method returns false and a banner should not be shown for this region.
    • If showAlertNotice = true, move to the next check.
  2. Was the most recent SDK Publish configured to re-consent users? This is controlled by the presence of 2 values. 1) A LastReconsentDate property in JSON with non-null value. 2) A OneTrustLastReconsentDate value saved on disk

    • If the LastReconsentDate JSON is newer than the OneTrustLastReconsentDate on disk, the method returns true and a banner should be shown.
    • If no, move to the next check
  3. Is the geolocation rule configured for automatic re-consent AND did the user's automatic re-consent timer expire? This is controlled by measuring the difference between OneTrustLastConsentDate saved on disk and the Current Date and seeing if it is greater than or equal to OneTrustReconsentFrequencyDays in the JSON saved on disk. The SDK considers the date itself and not the time consent was given. For example, if the re-consent period is set to 1 day in my geolocation rule and the user provides consent at 11:59pm GMT, the banner will reappear at 12:00am GMT (1 minute later, but the next day).

    • If yes, the method returns true and a banner should be shown.
    • If no, move to the next check
  4. Is Cross Device Consent enabled and were 100% of Purposes synced? This is controlled by the profile.sync.allPurposesUpdatedAfterSync property in JSON being true.

    • If yes, the method returns false and a banner should not be shown. This is because each of the Categories/Purposes managed by the SDK were 100% synced from the user's profile on the OneTrust server.
    • If no, move to the next check.
  5. Is Cross Device Consent enabled and is the user being exposed to new Categories/Purposes since the last time their consent was saved? This would only occur if Cross Device Consent is enabled and there was a new publish to the SDK which exposes new Categories/Purposes that have at least 1 SDK assigned to it.

    • If yes, the method returns true and a banner should be shown.
    • If no, move to the next check.
  6. Has the user previously given consent and is that consent stored at disk?

    • If yes, the method returns false and a banner should not be shown.
    • If no, the method returns true and a banner should be shown because this is the first time they are being asked to give consent on the app.
  7. Has a new category been added post giving consent?

    • If yes, the method returns true and a banner should be shown again because user needs to give consent to the new category.
    • If no, the method returns false and a banner should not be shown.

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.

Consent Values

OneTrust universally uses the following values for consent status:

Consent valueDescription
1Consent given
0Consent not given
-1Consent not yet gathered, or SDK not initialized

Listening for Consent Changes

The OneTrust SDK broadcasts consent events when you call startSDK() and when consent values change. You can use these events and consent values to trigger some action. Your app can listen to either the categories itself or each individual SDK you want to manage. OneTrust recommends setting up observers on the category level to minimize the amount of observers you have to initialize.

Use Case: Applications needs observers for the SDKs or Categories that require some action to be taken when a user gives/withdraws their consent.

Example: When a user opts out of the "Sale of Personal Data" category, set a privacy or opt out flag in Targeting SDKs in scope so no personalized ads or ads of any kind are shown to the user.

Call this method for each category you wish to start observing:

window.OneTrust.observeChanges("C0004")

Once a category is observed, an event will be fired whenever the consent for that category changes. The listener carries a payload with the categoryId as a string and consentStatus as an integer.

document.addEventListener('C0004',(payload) => {
    console.log("The new status of " + payload.categoryId + " is now " + payload.consentStatus)
}, false)

Stop listening for consent changes by calling the following for each category you'd like to cancel:

window.OneTrust.stopObservingChanges("C0004")

Querying for Consent

Query the current consent status for any of the categories included in your application. This can be used to determine what privacy action is needed at app launch or anytime the consent status is needed without being notified by an event broadcast. Simply pass in the Category ID (eg. C0001) and the method will return the current consent status (integer value).

window.OneTrust.getConsentStatusForCategory("C0004", (status) => {
        console.log("Queried consent status for C0004 is "+status)
    })

UI Interaction Events

📘

Note

UI Interaction Events are only relevant if the app is using the out of the box OneTrust UI. If you have built your own UI, disregard this section.

When a User interacts with the OT SDK UI, the SDK sends an interaction event that the application can listen for and action on.

Use Case: The app needs to trigger certain actions based on interaction with the UI.

Use Case 2: In the event that broadcasts cannot be used to action on consent, the app can rely solely on interaction events and querying for consent to fire/suppress SDKs.

Example 1: User selects the "Confirm My Choices" button on the OT Preference Center UI, which saves their consent choices. An app might want to listen for the onPreferenceCenterConfirmChoices() to show a success toaster to the user and navigate them to the App's home page.

Example 2: In lieu of broadcast events, the app can listen for allSDKViewsDismissed to know when the OneTrust UI has been dismissed and query for user consent. It can then use this consent to fire/suppress SDKs.

After the UI is dismissed from your application, a document event is broadcast. You can listen for this event to detect the UI dismissed.

document.addEventListener('allSDKViewsDismissed', () =>{
    console.log("All OneTrust Views dismissed")
}, false)

Types of other events:

Event NameDescriptionPayload
onShowBannerTriggered when banner is shownnull
onHideBannerTriggered when banner is closednull
onBannerClickedAcceptAllTriggered when user allows all consent from bannernull
onBannerClickedRejectAllTriggered when user rejects all consent from bannernull
onShowPreferenceCenterTriggered when Preference Center is displayednull
onHidePreferenceCenterTriggered when Preference Center is closednull
onPreferenceCenterAcceptAllTriggered when user allows all consent from Preference Centernull
onPreferenceCenterRejectAllTriggered when user rejects all consent from Preference Centernull
onPreferenceCenterConfirmChoicesTriggered when user clicked on save choices after updating consent values from Preference Centernull
onShowVendorListTriggered when vendor list UI is displayed from an IAB banner/ IAB Preference centernull
onHideVendorListTriggered when vendor list UI is closed or when back button is clickednull
onVendorConfirmChoicesTriggered when user updates vendor consent / legitimate interests purpose values and save the choices from vendor listnull
onVendorListVendorConsentChangedTriggered when user updates consent values for a particular vendor id on vendor list UI{vendorId:String, consentStatus:Int}
onVendorListVendorLegitimateInterestChangedTriggered when user updates Legitimate interests values for a particular vendor id on vendor list UI{vendorId:String, legitInterest:Int}
onPreferenceCenterPurposeConsentChangedTriggered when user updates consent values for a particular category on Preference Center UI{purposeId:String, consentStatus:Int}
onPreferenceCenterPurposeLegitimateInterestChangedTriggered when user updates Legitimate interest values for a particular category on Preference Center UI{purposeId:String, legitInterest:Int}
allSDKViewsDismissedTriggered when all the OT SDK Views are dismissed from the view hierarchy.{interactionType:String}

Special Configurations

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 SDK, 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.

window.OneTrust.getOTConsentJSForWebview((js) => {
        //inject javascript into webview
    })

Example output:

var OTExternalConsent = {
  "USPrivacy": "1---",
  "addtlString": "",
  "consentedDate": "Tue, 6 Apr 2021 16:13:41 +0100",
  "groups": "C0002:1,C0003:1,C0005:0,C0004:0,C0001:1",
  "tcString":"CPEPMp6PEPMp6AcABBFRBUCgAAAAAAAAAChQHrAA...",
  "gppString":"DBABzw~1YNY~BVQqAA...."
}

Important

It's recommended that the application call getOTConsentJSForWebview when you need to render a WebView. This ensures the payload is up to date based on the user's latest consent.

You can view more information (including FAQs) in the native documentation here: iOS Android

Get UI Data as JSON

After initialization, the data used to build a preference center or banner can be retrieved easily using the following methods. Each has a success and error handler, so if the download fails and there is no cached data, errors can be handled gracefully. This can also be used to determine whether or not OneTrust has the data required to operate offline (e.g. if getBannerData does not return an error, at least one download has completed successfully and the required data is present to render a banner.)

 window.OneTrust.getBannerData((data) => {
        console.log(`Banner Data = ${JSON.stringify(data)}`)
    }, (error) => {
        console.error(`No banner data! \n Error: ${error}`)
    })

    window.OneTrust.getPreferenceCenterData((data) => {
        console.log(`Preference Center Data = ${JSON.stringify(data)}`)
    }, (error) => {
        console.error(`No Preference Center data! \n Error: ${error}`)
    })

App Tracking Transparency

If enabled in your template, OneTrust can render a pre-prompt UI and then show the App Tracking Transparency prompt immediately after. You can view more information about this here.

The App Tracking Transparency Pre-Prompt can be shown by calling the below function. OneTrust.devicePermission.idfa is an enum for the type of permission. On Android and iOS versions < 14, requesting permission of type ifda will resolve a promise with a value of -1 every time.

showConsentUI

window.OneTrust.showConsentUI(window.OneTrust.devicePermission.idfa, status =>{
    console.log(`The new ATT Status is ${status}`)
})

Customize User Interfaces

This section is optional as most UI configurations are primarily made through the OneTrust tenant. If your app has a use case where it needs make additional configurations (e.g. font family) otherwise not available in the tenant OR if it needs to control the UI configurations locally, you can use these custom configurations.

📘

Custom Fonts

Custom Fonts are only supported on iOS through Ionic/Cordova. Android does not support Custom Fonts through uxParams.

Android - Custom styling with uxParams JSON

OneTrust allows you to add custom styling to the UI by passing in a formatted JSON. Build out your JSON by following the guide in the OneTrust Developer Portal.

Simply pass in the JSON in params argument of the startSDK method when initializing

// pass JSON in params
const params = {  
    syncParams: {  
      identifier: '[[email protected]](mailto:[email protected])',  
      syncProfileAuth:'eyJhb...',  
    },  
    countryCode:"US",  
    regionCode: "CA",  
    androidUXParams: uxJson  
  }

//pass params in startSDK
window.OneTrust.startSDK(storageLocation,domainIdentifer,languageCode,params,(status) => {
    console.log("SDK Downloaded Successfully!")
},(error) =>{
  console.log("SDK Failed to initialize! Error = "+error)  
})

iOS - Custom styling with uxParams Plist

Custom styling can be added to your iOS app 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 <Cordova/CDVViewController.h>
#import <Cordova/CDVAppDelegate.h>
#import <OTPublishersHeadlessSDK/OTPublishersHeadlessSDK.h>

@interface AppDelegate : CDVAppDelegate <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
{
    self.viewController = [[MainViewController alloc] init];
    [OTPublishersHeadlessSDK.shared setUiConfigurator:self]; //set UIConfigurator to Self
    return [super application:application didFinishLaunchingWithOptions:launchOptions];
}


- (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

Get the Data Subject Identifier

By default, OneTrust sets a random GUID for all users. You can use the methods below to retrieve the current identifier.

Get Current Data Subject Identifier

window.OneTrust.getCachedIdentifier((identifier) => {
          console.log(`Data Subject Identifier is ${identifier}.`)
        })

Programmatically Dismiss the UI

This method is used to programmatically force close the UI:

window.OneTrust.dismissUI()