Skip to main content

CMP JavaScript API

The Osano Consent Management Platform (CMP) JavaScript API documentation details its publicly available features.

The JavaScript API makes functions, properties, and events available to developers so that you can easily implement additional functionality based on the visitor's consent status (e.g., load scripts upon visitor consent being granted).

Important Notes

  • ⚠️ Utilizing this API to modify or disrupt Osano CMP's intended functionality is strongly discouraged. It may cause your site to not be compliant with privacy laws and regulations; while you have the ability to make such a change, it is not sanctioned by or approved by Osano and proceeding with the change will automatically terminate Section 4.7 of our Terms of Service which is our "No Fines Pledge". It may also cause defective behavior in future revisions.
  • ⚠️ The Osano CMP script, osano.js, must be the very first script in the document. Loading or injecting any other script prior to Osano CMP may result in it being unable to ensure compliance with regional consent laws. The one exception is using the Pre-load interface as necessary. See Installing Osano for more details.

Contents

Pre-load and window.Osano()

You can hook into the JavaScript API before Osano CMP loads by adding this script to the page before osano.js:

;(function(w,o,d){w[o]=w[o]||function(){w[o][d].push(arguments)};w[o][d]=w[o][d]||[]})(window,'Osano','data');

It creates a window.Osano() function that you can use to push arguments to the JavaScript API. You can add event listeners and set properties. For example:

<html>
<head>
<script>
;(function(w,o,d){w[o]=w[o]||function(){w[o][d].push(arguments)};w[o][d]=w[o][d]||[]})(window,'Osano','data');

window.Osano('onInitialized', consent => console.log('Osano.js initialized', consent));
window.Osano('onCookieBlocked', cookie => console.debug('Osano.js blocked cookie:', cookie));
window.Osano('userData', 'example user data');
</script>
<script src="https://cmp.osano.com/[...]/osano.js"></script>
...

window.Osano() can continue to be used after Osano CMP loads.

Adding Event Listeners

To add an event listener with the window.Osano() function, call it with two arguments: the event name and the callback. The same events are available to both the pre-load function as the JavaScript API but their names are in "onEventName" format:

Usage:

// window.Osano('onEventName', callback);
// example:
window.Osano('onUiChanged', (component, stateChange) => {
if (component === 'drawer' && stateChange === 'show') {
console.log('Preferences drawer has been opened.');
}
});

Setting Properties

Adding property values with the window.Osano() function takes two arguments, the property name and the value. Only "setter" properties on the JavaScript API are supported:

Usage:

// window.Osano('propertyName', value);
// example:
window.Osano('userData', 'some user data');

JavaScript API Reference

The Osano CMP JavaScript API is available after initialization on the browser's window object: window.Osano.cm. It is available immediately after the Osano CMP script (osano.js) in the document. You do not need to wait for Osano.cm to become available.

Use of deprecated features is not recommended as they may be removed in a future revision.

Functions

Each of these functions are accessible via window.Osano.cm. For example, window.osano.cm.showDrawer().

function addEventListener(eventType /* string */, callback /* function */)

Adds an event listener. See the Events section for events, callback arguments and examples.

deprecated function emit(eventName)

Calling this function with the support event below will trigger its described behavior. This function has been superseded by other functions and may be removed in a future revision.

Supported event:

  • osano-cm-dom-info-dialog-open: equivalent to window.Osano.cm.showDrawer()

function getConsent()

Returns the Consent Object.

function hideDialog()

Hides the Dialog.

function hideDoNotSell()

Hides the "Do not sell or share" modal.

function hideDrawer()

Hides the Drawer.

function hideWidget()

Hides the Widget.

function off(eventType /* string */, callback /* function */)

Equivalent to window.Osano.cm.removeEventListener(eventType, callback).

function on(eventType /* string */, callback /* function */)

Equivalent to window.Osano.cm.addEventListener(eventType, callback).

function ready(readyApi /* string */, options /* object */)

This function allows Osano CMP to integrate with third-party APIs. The customer is responsible for calling it with the correct parameters when the other API is ready.

Supported Third-Party APIs
  1. Shopify

    Parameters:

    • readyApi: "shopify"
    • options: undefined

    Example:

    window.Shopify.loadFeatures([{
    name: 'consent-tracking-api',
    version: '0.1',
    }], function(error) {
    if (!error) {
    try {
    window.Osano.cm.ready('shopify');
    } catch (error) {
    console.error('Osano must be loaded before initializing the Shopify API.');
    }
    }
    });

function render()

Forces the DOM components of Osano CMP to re-render.

function removeEventListener(eventType /* string */, callback /* function */)

Removes the callback from the list of listeners for the eventType. The callback argument must be the same object that was passed to addEventListener. See the Events and Using Events sections for more details.

function showDialog()

Shows the Dialog.

function showDoNotSell()

Shows the "Do not sell or share" modal.

Note that the dialog will close itself when the user saves or dismisses it. You do not need to manually call hideDoNotSell().

Example usage:

<body>

<a href="#do-not-sell">My privacy choices</a>

<script>
const privacyLink = document.querySelector('a[href="#do-not-sell"]');
privacyLink.addEventListener('click', event => {
event.preventDefault();
Osano.cm.showDoNotSell();
});
</script>
</body>

function showDrawer()

Shows the Drawer.

function showWidget()

Shows the Widget.

Properties

Each of these functions are accessible via window.Osano.cm. For example, window.osano.cm.analytics.

read-only analyticsboolean

Returns true if the ANALYTICS property of the Consent Object is ACCEPT. Returns false otherwise.

read-only cmpVersionstring

Returns the Osano CMP version (e.g. "2022.12.1").

deprecated | read-only countryCodestring

Superseded by jurisdiction

Returns the lowercase ISO 3166 two-letter code of the country where Osano CMP believes the user is located.

Example:

console.log(window.Osano.cm.countryCode);
// "us"

read-only drawerOpenboolean

Returns true if the Drawer is visible or false if it is not.

read-only dialogOpenboolean

Returns true if the Dialog is visible or false if it is not.

read-only jurisdictionstring

Returns the lowercase country and subdivision codes according to ISO 3166-1 and 3166-2 where Osano CMP believes the user is located.

Example:

console.log(window.Osano.cm.jurisdiction);
// "us-tx"

localestring

Gets or sets Osano CMP's current locale in IETF language-tag format. Supports two-character primary language and optional two-character region sub-tag.

Setting to an available language will fetch the localization from Osano's servers and update Osano CMP's visual components.

Setting this property to an unavailable or invalid language will throw an Error.

read-only marketingboolean

Returns true if the MARKETING property of the Consent Object is ACCEPT. Returns false otherwise.

read-only modestring

Returns a value corresponding to one of the Compliance modes:

  • debug ⇒ Discovery/Listener
  • permissive ⇒ Permissive
  • production ⇒ Strict

read-only optOutboolean

Returns true if the OPT-OUT property of the Consent Object is ACCEPT. Returns false otherwise.

read-only personalizationboolean

Returns true if the PERSONALIZATION property of the Consent Object is ACCEPT. Returns false otherwise.

deprecated | read-only storageobject

Returns an object wrapping the getConsent() function. This property has been superseded by the fuller JavaScript API and may be removed in a future revision.

userDatastring

User data is used exclusively for Cross-Device Consent. Your configuration must have this feature enabled for it to work. Otherwise, setting it does nothing and it will always return an empty string.

If Cross-Device Consent is enabled, user data may be used to store and retrieve consent across devices. In order for this to work it must be set to a user identifier, something unique and consistent for each user. The value is stored locally on a user's device along with their consent. Before being recorded, it is one-way hashed. The raw value is never sent to Osano's servers and cannot be retrieved by Osano.

When setting userData, the value may be either a string or a number. Numbers will be converted to string values automatically. The value must be 128 characters or fewer.

Example:

window.Osano.cm.userData = 123456;
console.log(window.Osano.cm.userData);
// '123456'

⚠️ Note: Cross Device Consent support is not compatible with configurations that are running Legacy Browser Support. In order to use this feature, you will need to disable Legacy Browser Support first.

⚠️ Caution: do not use this capability in a way that will take you out of compliance with privacy laws and regulations.

Events

osano-cm-analytics

This is a one-time event, meaning the callback will be called at most once. The event will dispatch when the ANALYTICS consent is given (the value becomes ACCEPT). If it is never given, the event will not be dispatched. A new listener added when consent has already been given (i.e. Osano.cm.getConsent()['ANALYTICS'] === 'ACCEPT') will be called immediately.

The callback does not receive any arguments.

Example:

Osano.cm.addEventListener('osano-cm-analytics', () => console.log('Consent granted for analytics.'));

This event will dispatch when a cookie is blocked from being set in the visitor's browser.

The callback function receives a string that indicates the name of the cookie that was blocked.

Example:

Osano.cm.addEventListener('osano-cm-cookie-blocked', (cookie) => console.log('Cookie blocked:', cookie));
document.cookie = "marketing-cookie=John Doe; path=/";

// Assuming no consent for marketing and the "marketing-cookie" is classified as such, the console will output:
// Cookie blocked: marketing-cookie

This event will dispatch when the visitor toggles a consent category. It only indicates that the visitor has changed this option and does not reflect the consent being saved.

The callback function receives an object with a single key-value pair {"CATEGORY_NAME": "ALLOW_OR_DENY"} indicating the category the visitor toggled and its new value.

Example:

Osano.cm.addEventListener('osano-cm-consent-changed', (change) => console.log('Category toggled:', JSON.stringify(change)));

// When a visitor changes ANALYTICS from ACCEPT to DENY, the console will show:
// Category toggled: {"ANALYTICS":"DENY"}

This event will dispatch immediately after osano-cm-consent-saved if the visitor is registering a new consent (i.e. they have never consented before or their consent was expired).

The callback function receives a full Consent Object representing the visitor's consent.

This event will dispatch when the visitor saves their consent preferences. If the consent has been saved already, the callback will be called immediately.

The callback function receives a full Consent Object representing the visitor's consent.

osano-cm-iframe-blocked

This event will dispatch when an iframe is blocked from being loaded in the visitor's browser.

The callback function receives a string that indicates the src value of the iframe that was blocked.

Example:

Osano.cm.addEventListener('osano-cm-iframe-blocked', (src) => console.log('Iframe blocked:', src));

// Example console output:
// Iframe blocked: https://analytics-tracking-frames.example/

osano-cm-initialized

This event will dispatch when Osano CMP is initialized. If it has already initialized when a listener is added for this event, the callback will be called immediately.

The callback function receives a Consent Object that indicates the current visitor's provided consent or undefined when the visitor has not yet given consent.

osano-cm-locale-updated

This event will dispatch when the locale is updated even if the new locale is the same.

The callback function receives a string with the updated locale value.

Note: the callback will not be called if the locale is invalid or unavailable.

Example:

Osano.cm.addEventListener('osano-cm-locale-updated', (locale) => console.log('Locale updated:', locale));
Osano.cm.locale = 'en';

// Example console output:
// Locale updated: en

osano-cm-marketing

This is a one-time event, meaning the callback will be called at most once. The event is dispatched when the MARKETING consent is given (the value becomes ACCEPT). If it is never given, the event will not be dispatched.

The callback does not receive any arguments.

A new listener added when consent has already been given (i.e. Osano.cm.getConsent()['MARKETING'] === 'ACCEPT') will be called immediately.

Example:

Osano.cm.addEventListener('osano-cm-marketing', () => console.log('Consent granted for marketing.'));

osano-cm-opt-out

This is a one-time event, meaning the callback will be called at most once. The event is dispatched when the OPT_OUT value becomes ACCEPT (indicating that the visitor is opting out). If the value never becomes ACCEPT, the event will not be dispatched. See IAB CCPA Framework && Do Not Sell for more information on opting out.

The callback does not receive any arguments.

A new listener added when consent has already been given (i.e. Osano.cm.getConsent()['OPT_OUT'] === 'ACCEPT') will be called immediately.

Example:

Osano.cm.addEventListener('osano-cm-opt-out', () => console.log('Visitor has opted out.'));

osano-cm-personalization

This is a one-time event, meaning the callback will be called at most once. The event is dispatched when the PERSONALIZATION consent is given (the value becomes ACCEPT). If it is never given, the event will not be dispatched.

The callback does not receive any arguments.

A new listener added when consent has already been given (i.e. Osano.cm.getConsent()['PERSONALIZATION'] === 'ACCEPT') will be called immediately.

Example:

Osano.cm.addEventListener('osano-cm-personalization', () => console.log('Consent granted for personalization.'));

osano-cm-script-blocked

This event will dispatch when a script is blocked from being run in the visitor's browser.

The callback function receives a string that indicates the src value of the script that was blocked.

Example:

Osano.cm.addEventListener('osano-cm-script-blocked', (src) => console.log('Script blocked:', src));

// Example console output:
// Script blocked: https://analytics-tracking-scripts.example/tracker.js

osano-cm-storage

This is a one-time event, meaning the callback will be called at most once. The event is dispatched when the STORAGE consent is given (the value becomes ACCEPT). If it is never given, the event will not be dispatched. See Osano and the IAB Framework (TCF 2.0) for more information on the Storage category.

The callback does not receive any arguments.

A new listener added when consent has already been given (i.e. Osano.cm.getConsent()['STORAGE'] === 'ACCEPT') will be called immediately.

Example:

Osano.cm.addEventListener('osano-cm-storage', () => console.log('Consent granted for storage.'));

osano-cm-ui-changed

This event will dispatch when a UI component is shown or hidden. It receives two arguments: component and stateChange.

Values for component:

  • dialog
  • drawer
  • widget

Values for stateChange:

  • hide
  • show

Example:

Osano.cm.addEventListener('osano-ui-changed', (component, stateChange) => {
if (component === 'drawer' && stateChange === 'show') {
console.log('Preferences drawer has been opened.');
}
});

Using Events

Osano CMP automatically prevents scripts with a src attribute from loading until those scripts have been approved and categorized. Although Osano CMP does prevent inline scripts from creating new scripts and iframes based on consent status and categorization, it does not prevent inline scripts from executing. Therefore it is generally recommended that developers do not implement event listening unless code within inline scripts depends on consent status.

Some scenarios that might require event listening are:

  • Your inline script writes a script or iframe to the document and expects that element to be immediately available.
  • Your inline script depends upon the availability of a script that might be blocked by Osano CMP in certain regions until the consent has been granted by the visitor.
  • Your organization loads content asynchronously or makes other content decisions that depend on visitor consent (e.g. the text of the article cannot be loaded until the visitor has accepts or denies a category).

The Osano.cm object is available immediately after the CM script in the document. You do not need to wait for the Osano.cm object to become available.

Format

{ 
ANALYTICS: "ACCEPT",
MARKETING: "DENY",
PERSONALIZATION: "DENY",
ESSENTIAL: "ACCEPT",

/*special IAB categories*/
OPT-OUT: "ACCEPT",
STORAGE: "DENY"
}

Categories and Values

The Consent Object has the following categories: Analytics, Marketing, Personalization, Essential, Opt-Out, and Storage.

Each of these categories will have a value of either ACCEPT or DENY.

The Opt-Out and Storage categories are both connected to the Interactive Advertising Bureau (IAB). Opt-Out is related to the IAB CCPA framework. This corresponds to the "Do Not Sell" switch seen in the US version of the preferences Drawer.

The "Storage" category is related to the IAB TCF 2.0 framework. This corresponds to the storage option seen in the EU when TCF 2.0 is enabled.

Note: both of these values are present on the Consent Object (e.g. when calling window.Osano.cm.getConsent() or in the callback of a relevant event) even if you are not utilizing the TCF 2.0 feature. If you are not utilizing TCF 2.0, the "Storage" category will default to DENY.