Web CMP JavaScript Methods

This page provides a list of all public methods exposed by the Web CMP script.

Close Cookie Banner

MethodOneTrust.Close()
DescriptionDismisses the cookie banner and sets the default consent model.

Allow All Consent

MethodOneTrust.AllowAll()
DescriptionEnables consent for all categories/purposes, hosts, and vendors.

Reject All Consent

MethodOneTrust.RejectAll()
DescriptionDisables consent for all categories/purposes, hosts, and vendors, except those marked as strictly necessary.

Show Preference Center

MethodOneTrust.ToggleInfoDisplay()
DescriptionDisplays the Preference Center UI.

Show Cookie Banner (Single Page Application)

MethodOneTrust.LoadBanner()
DescriptionLoads the cookie banner (if configured in geo rules) when the OptanonAlertBoxClosed cookie is removed.
Pre-requisiteEnsure that ‘Enable single page application support’ is turned on in your script’s publish pane.
ConsiderationsRemove the onetrust-consent-sdk element from the page.
Note: Calling LoadBanner() will reintroduce this element, and duplicate instances may cause UI issues.

Insert Script

MethodOneTrust.InsertScript(url, selector, callback, options, groupId, async)
DescriptionInjects scripts or files dynamically once user consent is granted.
Parametersurl (string): Source URL for the script tag.

selector (string): Specifies the container element for the script tag. Acceptable values include "head", "body", or a custom element ID (e.g., "{element_id}").

callback (string): (Optional) Callback function to execute after the script tag has been successfully inserted.

options (function): (Optional) Defines custom behaviors to execute after the script has been inserted. See below for more information.

groupId (string): Purpose/category ID.

async (boolean): Indicates whether the script should be loaded asynchronously. When set to true, the script loads in parallel without blocking page rendering.

options

// set to true to delete all selector content before inserting script
options.deleteSelectorContent(boolean)

// set to true to show selector after inserting script
options.makeSelectorVisible(boolean)

// set the IDs of arbitrary elements to show after inserting script
options.makeElementsVisible(array[string])

// set the IDs of arbitrary elements to delete after inserting script 
options.deleteElements(array[string])

Sample reference

OneTrust.InsertScript('https://www.w3schools.com/js/myScript1.js','body', null, null, 'C0004', true);

Insert HTML

MethodOneTrust.InsertHTML(element, selector, callback, options, groupId)
DescriptionInjects HTML elements dynamically once user consent is granted.
Parameterselement (string): HTML element string to be inserted

selector (string): ID of the HTML parent element where the new element will be inserted. Example: "parent_id".

callback (string): (Optional) Callback function to execute after the HTML element has been successfully inserted.

options (function): (Optional) Defines custom behaviors to execute after the HTML element has been inserted. See below for more information.

groupId (string): Purpose/category ID.

options

// set to true to delete all selector content before inserting element
options.deleteSelectorContent(boolean)

// set to true to show selector after inserting element
options.makeSelectorVisible(boolean)

// set the IDs of arbitrary elements to show after inserting element
options.makeElementsVisible(array[string])

// set the IDs of arbitrary elements to delete after inserting element 
options.deleteElements(array[string])

Sample reference

OneTrust.InsertHtml('<div>some div</div>', '#container', null, null, 'C0004');

Block Google Analytics

MethodOneTrust.BlockGoogleAnalytics(gaId, groupId)
DescriptionBlock Google Analytics when consent has not been given. Sets window['ga-disable-${gaID}']
ParametersgaId (string): Google Analytics ID.

groupId (string): Purpose/category ID.

Trigger Google Analytics Event

MethodOneTrust.TriggerGoogleAnalyticsEvent(category, action, label, value)
DescriptionUsed to trigger Google Analytics event. We can by inspecting DataLayer event trackOptanonEvent.
Parameterscategory (string): category
action (string): action
label (string): label
value (string): value

Example

OneTrust.TriggerGoogleAnalyticsEvent(category, action, label, value);

Is OptanonAlertBoxClosed Cookie Set

MethodIsAlertBoxClosed()
DescriptionWhen true, OptanonAlertBoxClosed cookie is set. This will result in the Banner not being shown to the user, unless re-consent is flagged on initialization.
Parametersn/a
Returnsboolean

Example

OneTrust.IsAlertBoxClosed();

Is OptanonAlertBoxClosed and Valid

MethodIsAlertBoxClosedAndValid()
DescriptionWhen true, OptanonAlertBoxClosed cookie is set. This will result in the Banner not being shown to the user, unless re-consent is flagged on initialization.
Parametersn/a
Returnsboolean

Example

OneTrust.IsAlertBoxClosedAndValid();

Set OptanonAlertBoxClosed Cookie

MethodSetAlertBoxClosed()
DescriptionUsed to set OptanonAlertBoxClosed cookie based on isOptanonAlertBoxCookiePersistent.
Parametersn/a
Returnsn/a

Example

OneTrust.SetAlertBoxClosed();

On Consent Changed Callback

MethodOnConsentChanged(callback)
DescriptionCallback for consent changed event.
Parameterscallback (function): callback
Returnsn/a

Example

OneTrust.OnConsentChanged(function() {});

Get Domain Data

MethodGetDomainData()
DescriptionGet information about the cookie script - data includes, consent models, cookies in preference centre, etc.
Parametersn/a
Returnsobject

Example

OneTrust.GetDomainData();

Returns

Contact OneTrust

Get Vendor Consent Requests

MethodgetVendorConsentsRequestV2()
DescriptionWill return getInAppTCData to support mobile applications. See more information IAB TCF 2.0 SDK Developer Guide.
Parametersn/a
Returnsobject

Example

OneTrust.getVendorConsentsRequestV2();

Returns

Contact OneTrust

Test Log

MethodtestLog()
DescriptionView the configured script details and verify implementation using a new Javascript method in the browser console.
Parametersn/a
Returnsconsole log

Example

OneTrust.testLog();

Returns

- Domain with which the script is associated
- Consent model for the region
- If banner is shown or not shown
- Whether consent has been given (OptanonAlertBoxClosed presence)
- Current Category Statuses 
- General Vendor Ids
- Geolocation and Template name
- List of active cookies with associated category IDs, host IDs, and vendor IDs

Change Language

MethodchangeLanguage(lang)
DescriptionProgrammatically change the language that the banner and preference center are presented in on the page. This will throw an exception if the language has not been configured for the displayed template.
Parameterslang(string): 2-digit ISO 639 language code. Make sure to configure the language for the Template and published.
Returnsn/a

Example

OneTrust.changeLanguage("en"); // English
OneTrust.changeLanguage("fr"); // French
OneTrust.changeLanguage("de"); // German
OneTrust.changeLanguage("ja"); // Japansese
OneTrust.changeLanguage("pt"); // Portuguese

Fetch and Download Preference Center

MethodFetchAndDownloadPC()
DescriptionFetch the Preference Center JSON and render it to view.
Parametersn/a
Returnsn/a

Example

OneTrust.FetchAndDownloadPC();

Get Geolocation Data

MethodgetGeolocationData()
DescriptionReturns the location of the user as determined by the CloudFlare IP service
Parametersn/a
ReturnsJSON

Get CSS

MethodgetCSS()
DescriptionReturns the CSS for the CMP.
Parametersn/a
Returnsstring

Example

OneTrust.getCSS();

Returns

#onetrust-banner-sdk{ ... }

Update Consent

MethodUpdateConsent(groupIdType,bitValue)
DescriptionEnable or disable consent for a category, host, or general vendor by providing the respective bit value
ParametersgroupIdType(string),bitValue(string)
Returnsn/a

Example

OneTrust.UpdateConsent("Category","C0003:1"); //Enables consent for cookie category 3
OneTrust.UpdateConsent("Category","C0003:0"); //Disable consent for cookie category 3
OneTrust.UpdateConsent("Category","C0001:1,C0002:1,C0003:0"); //Enable consent for cookie category 1 and 2, Disable consent for cookie category 3
OneTrust.UpdateConsent("Host","H2:1"); //Enable consent for Host H2
OneTrust.UpdateConsent("Host","H2:0"); //Disable consent for Host H2
OneTrust.UpdateConsent("General Vendor","V33:1"); //Enable consent for General Vendor V33
OneTrust.UpdateConsent("General Vendor","V33:0"); //Disable consent for General Vendor V33

Set Data Subject Id

MethodsetDataSubjectId(dataSubjectId,isAnonymous, identifierType)
DescriptionSet an identifier for the current user. Optionally provide an identifier type or let it default to the default identifier set in Geolocation rules. More information on identifying users and setting default identifiers in Unified profile.
ParametersdataSubjectId (string), isAnonymous (boolean = false), identifierType (string = Default Identifier)
Returnsn/a
OneTrust.setDataSubjectId("someId") //sets Id to "someId", defaults to isAnonymous = false and identifierType = "Cookie Unique Id" or any default identifier set in geolocation rules
OneTrust.setDataSubjectId("someId", true) //sets Id to "someId", sets isAnonymous to true and defaults to identifierType = "Cookie Unique Id" 
OneTrust.setDataSubjectId("[email protected]", false,"Email") // sets Id to "someId", sets isAnonymous to false and sets identifierType to "Email"

Sync Consent Profile

MethodsyncConsentProfile(dataSubjectId,JWT_Token,isAnonymous)
DescriptionRetrieves or logs consent for a user depending on the toggle status of 'Override server consent'. See more information here. When consent is retrieved from the server, you can see the payload returned in the Network calls via the "preferences" call. This method will update the value of OptanonConsent.
ParametersdataSubjectId (string), JWT_Token (string) isAnonymous (boolean = false)
Returnsn/a

Example

OneTrust.syncConsentProfile("Identifier","JWT_Token",false)

Set Consent Profile

MethodsetConsentProfile(payload)
DescriptionUpdate the consent values of OptanonConsent
Parameterspayload (string) - see example below
Returnsn/a

Example

OneTrust.setConsentProfile({"purposes": 
                            [{"Id":"PURPOSE_ID","TransactionType":"CONFIRMED"},
                             {"Id":"PURPOSE_ID","TransactionType":"NOT_GIVEN"},
                             {"Id":"PURPOSE_ID","TransactionType":"CONFIRMED"}],
                            "identifier":"dataSubjectId"});

Send Consent Receipt

MethodSendReceipt
DescriptionSend a receipt immediately. The receipt will be backdated to the last interaction date. This is particularly useful when not using Cross-Domain and Cross-Device Consent but still wanting to log a receipt immediately after identifying a data subject, creating, or updating their profile.
Parametersn/a
Returnsobject

Example

OneTrust.SendReceipt()

📘

For more information, see Unified Profile.

Get Data Subject Id

MethodgetDataSubjectId()
DescriptionRetrieves the data subject ID