# API

## Usage

The Didomi Web SDK exposes a complete API on the page via JavaScript for interacting with the Didomi platform. This allows your scripts to programmatically interact with the Didomi SDK. You can check the user consent status, register consents that you would collect yourself, and show/hide the Didomi UI.

### Didomi ready

The API is exposed on the `window.Didomi` object. All calls to the Didomi API (except for the standard IAB `__cmp` function) must be enclosed within a `window.didomiOnReady` callback to ensure that the SDK is ready before calling it:

{% tabs %}
{% tab title="Plain Javascript" %}

```javascript
<script type="text/javascript">
window.didomiOnReady = window.didomiOnReady || [];
window.didomiOnReady.push(function (Didomi) { 
    // Call other functions on the SDK
});
</script>
```

{% endtab %}

{% tab title="React" %}

```javascript
onDidomiReady(didomi) {
  console.log('Didomi Ready');
  // Call other functions on the SDK
}

...

<DidomiSDK
    ...
    onReady={this.onDidomiReady.bind(this)}
/>
```

{% endtab %}
{% endtabs %}

The `window.didomiOnReady` callbacks are called after the SDK is initialized and has loaded its configuration.

{% hint style="warning" %}
Setting `window.didomiConfig` in a `window.didomiOnReady` callback has no effect as the SDK is already initialized at that point. `window.didomiConfig` must be set at the root of the page and outside of any callback.
{% endhint %}

### postMessage API

If your JavaScript is not directly present on the page where the Didomi Web SDK is embedded but is present within an iframe on that page, you can communicate with the Didomi Web SDK through the `postMessage` API of the browser.

#### Available functions

Currently only `getCurrentUserStatus` is exposed via this API to allow reading the consent status of the user. To better understand its usage, you can refer to its [definition](#getcurrentuserstatus).

#### Messages structure

The Didomi API is exposed with the same structure as the [IAB CMP API](https://github.com/InteractiveAdvertisingBureau/GDPR-Transparency-and-Consent-Framework/blob/master/CMP%20JS%20API%20v1.1%20Final.md#without-safeframes-using-postmessage-).

The message to send should have the below form where:

* `command` is the name of the function on the `window.Didomi` object to call
* `parameter` is an array of parameters passed to the function called on the `window.Didomi` object
* `callId` is a unique value that will be sent back with the response from Didomi, allowing you to identify what call the response is for

```javascript
window.parent.postMessage({
  __cmpCall: 
    {
      command: "*command*", 
      parameter: [param1, param2, ...], 
      callId: *uniqueId*
    }
}, "*");
```

The Didomi Web SDK will send back the message below to your frame with the `postMessage` API containing a response for your command where:

* `returnValue` is the value returned by the API function called
* `success` is a boolean flag indicating whether the call was successful or not
* `callId` is the unique value provided as `callId` in your original message

```javascript
{
  __cmpReturn: 
    {
      returnValue: *returnValue*, 
      success: *boolean*, 
      callId: *uniqueId*
    }
}
```

#### Usage example

Here is a complete example of how to call one of the available functions of the postMessage API (`getCurrentUserStatus`) and collect its response:

```javascript
window.addEventListener(
  "message",
  function (event) {
    try {
      var data = typeof event.data === "string" ? JSON.parse(event.data) : event.data;

      if (data && data.__cmpReturn) {
        // data.__cmpReturn contains the response from the CMP
        if (data.__cmpReturn.callId === "get-current-user-status") {
          // This is the response to our call for getting the user status
          // The status is in data.__cmpReturn.returnValue
          // Do something
        }
      }
    } catch (e) {
      // An error happened when decoding the message data
      // Most likely, the message wasn't related to the CMP so do nothing
    }
  },
  false
);

window.parent.postMessage(
  {
    __cmpCall: {
      command: "getCurrentUserStatus",
      parameter: [],
      callId: "get-current-user-status",
    },
  },
  "*",
);
```

#### Determining the frame containing the Didomi CMP

The frame to send the `postMessage` to can be determined by the ancestor with a `.frames["__tcfapiLocator"]` child iframe present.

If your code runs in a direct iframe of the page containing the `window.Didomi` object then you can simply use window\.parent as the reference to send messages to.

If your code might run multiple levels removed from the frame containing the `window.Didomi` object, you can search for the correct frame to send a message to with the following code:

```javascript
var f = window;
var cmpFrame;

while (!cmpFrame) {
  try {
    if (f.frames["__tcfapiLocator"]) cmpFrame = f;
  } catch (e) {}

  if (f === window.top) break;

  f = f.parent;
}
```

***

## Didomi Consent String (DCS)

The Didomi Consent String (DCS) - `didomi_dcs` - is a binary format that replaces the traditional `didomi_token`, typically stored in cookies or local storage. [Click here](https://developers.didomi.io/cmp/didomi-consent-string) for more information.

{% hint style="warning" %}
**Note**: For consent notices utilizing a GDPR regulation with the IAB TCF framework, the TC String remains the source of truth and the Didomi Web SDK will work with both strings to create a unified view of consent choices that are reflected in the public API functions for the SDK.
{% endhint %}

The Didomi Consent String stores end-user choices for custom and Google ATP vendors, and custom and global purposes across all regulations. These vendors and purposes are assigned numeric IDs that are encoded in the Didomi Consent String and are used to identify the vendor or purpose, respectively.

Each time a notice is published, Didomi generates the numeric IDs for these vendors and purposes contained in the consent notice (if they do not already have numeric IDs). Numeric IDs can be accessed with the following API functions:

### getVendorNumericId()

Retrieve the numeric ID of a custom or Google ATP vendor for a consent notice.

**Parameters**

<table><thead><tr><th width="163">Name</th><th width="121">Type</th><th>Description</th></tr></thead><tbody><tr><td>Vendor SDK ID</td><td><code>string</code></td><td>The SDK ID belonging to the vendor for which you are retrieving the numeric ID</td></tr></tbody></table>

**Returns**

Numeric ID of the vendor.

**Example**

<details>

<summary><code>Didomi.getVendorNumericId("c:mycompany-AbCD1234")</code></summary>

```javascript
40512
```

</details>

### getVendorByNumericId()

Retrieve the vendor object for the specified numeric ID

**Parameters**

<table><thead><tr><th width="163">Name</th><th width="121">Type</th><th>Description</th></tr></thead><tbody><tr><td>Vendor numeric ID</td><td><code>number</code></td><td>The numeric ID belonging to the vendor for which you are retrieving the vendor object</td></tr></tbody></table>

**Returns**

Properties returned for a vendor object dependent on vendor class and declarations.

<table><thead><tr><th width="230">Property</th><th width="174">Data Type</th><th>Description</th></tr></thead><tbody><tr><td>didomiId</td><td><code>string</code></td><td>Didomi assigned vendor ID</td></tr><tr><td>id</td><td><code>string</code></td><td>Didomi SDK ID</td></tr><tr><td>namespace</td><td><code>string</code></td><td>Defines the vendor class</td></tr><tr><td>purposeIds</td><td><code>array</code></td><td>Opt-in purposes declared by a custom vendor (requires end-user consent)</td></tr><tr><td>deviceStorageDisclosureUrl</td><td><code>string</code></td><td>URL disclosing details for web or app storage</td></tr><tr><td>cookieMaxAgeSeconds</td><td><code>number</code></td><td>The longest lifespan of a cookie (in seconds)</td></tr><tr><td>lang_urls</td><td><code>array</code></td><td>Url objects representing language, policy url and legitimate interest url</td></tr><tr><td>name</td><td><code>string</code></td><td>Name of the vendor</td></tr><tr><td>namespaces</td><td><code>object</code></td><td><p>Can contain:</p><ul><li>Namespace objects with additional IDs for the vendor</li><li><code>num</code>: Didomi Consent String encoding/decoding numeric ID</li></ul></td></tr><tr><td>policyUrl</td><td><code>string</code></td><td>URL of the vendor's privacy policy</td></tr><tr><td>type</td><td><code>string</code></td><td>Whether vendor is 1st_party or 3rd_party</td></tr><tr><td>usesNonCookieAccess</td><td><code>boolean</code></td><td><p>Indicates the vendor’s use of non-cookie storage and access to information already stored on an end-user’s device.</p><ul><li><strong>True</strong>: non-cookie access is used.</li><li><strong>False:</strong> non-cookie storage and access to information already stored on an end-user's device is not used</li></ul></td></tr></tbody></table>

**Example**

<details>

<summary><code>Didomi.getVendorByNumericId(40512)</code></summary>

```javascript
{
    didomiId: "tomgccvvv-1234Cm3G",
    id: "c:tomgccvvv-MXUaCm3G",
    lang_urls: [],
    legIntPurposeIds: ['market_research', 'improve_products'],
    name: "Custom Vendor Example",
    namespace: "custom",
    namespaces: {
        num: 12345
    },
    policyUrl: "https://demoprivacypolicy.com",
    purposeIds: ["advertising", "select_basic_ads", "create_ads_profile"],
    type: "3rd_party",
    usesNonCookieAccess: true
}
```

</details>

### getPurposeNumericId()

Retrieve the numeric ID of a custom or global purpose for a consent notice.

**Parameters**

<table><thead><tr><th width="163">Name</th><th width="121">Type</th><th>Description</th></tr></thead><tbody><tr><td>Purpose numeric ID</td><td><code>string</code></td><td>The SDK ID belonging to the purpose for which you are retrieving the numeric ID</td></tr></tbody></table>

**Returns**

Numeric ID of the purpose

**Example**

<details>

<summary><code>Didomi.getPurposeNumericId("analytics_tracking")</code></summary>

```javascript
16819
```

</details>

### getPurposeByNumericId()

Retrieve the purpose object for the specified numeric ID

**Parameters**

<table><thead><tr><th width="163">Name</th><th width="121">Type</th><th>Description</th></tr></thead><tbody><tr><td>Purpose SDK ID</td><td><code>number</code></td><td>The numeric ID belonging to the purpose for which you are retrieving the purpose object</td></tr></tbody></table>

**Returns**

<table><thead><tr><th width="180">Property</th><th width="162">Data Type</th><th>Description</th></tr></thead><tbody><tr><td>description</td><td><code>object</code></td><td>Translations of the purpose description</td></tr><tr><td>id</td><td><code>string</code></td><td>Didomi SDK ID</td></tr><tr><td>name</td><td><code>object</code></td><td>Translations of the purpose name</td></tr><tr><td>namespace</td><td><code>string</code></td><td>Defines the purpose class</td></tr><tr><td>namespaces</td><td><code>object</code></td><td><p>Can contain:</p><ul><li>Namespace objects with additional IDs for the purpose</li><li><code>num</code>: Didomi Consent String encoding/decoding numeric ID</li></ul></td></tr></tbody></table>

**Example**

<details>

<summary><code>Didomi.getPurposeByNumericId(16819)</code></summary>

```javascript
{
  description: {
    en: "Marketing communication delivered to end-user",
    fr: "Communication marketing délivrée à l'utilisateur final"
  },
  id: "marketing-kKRJyAND",
  name: {
    en: "Marketing communication",
    fr: "Communication marketing"
  },
  namespace: "custom",
  namespaces: {
    num: 16951
  }
}
```

</details>

***

## Notice config

### getExperiment()

Get the currently configured [AB test (experiment)](https://developers.didomi.io/cmp/web-sdk/ab-tests) and the user information for that test.

**Parameters**

No parameter.

**Returns**

An object with the following properties:

| Name      | Type     | Description                                                                                                                                                                                                                                                      |
| --------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| id        | `string` | ID of the experiment as configured in your tag                                                                                                                                                                                                                   |
| group     | `string` | <p>Group that the user is assigned to for the experiment</p><p><code>control</code> if the user is part of the control group</p><p><code>test</code> if the user is part of the test group</p><p><code>null</code> if the user is not part of the experiment</p> |
| size      | `number` | Size of the test group (number between 0 and 1)                                                                                                                                                                                                                  |
| startDate | `string` | Start date of the test as ISO 8601 with millisecond precision                                                                                                                                                                                                    |

**Example**

```javascript
{
    "id": "experiment-id",
    "group": "control",
    "size": 0.1,
    "startDate": "2019-03-06T23:38:50.000Z"
}
```

### isRegulationApplied(regulation)

Check if a given regulation applies to the current user.

**Parameters**

| Name       | Type     | Description                                                        |
| ---------- | -------- | ------------------------------------------------------------------ |
| regulation | `string` | <p><code>gdpr</code> for GDPR</p><p><code>ccpa</code> for CCPA</p> |

**Returns**

A `boolean` indicating whether the user is subject to the regulation and support for the regulation is enabled for the website.

**Example**

```javascript
if (Didomi.isRegulationApplied('gdpr')) {
  // The user is subject to GDPR, do something
}

if (Didomi.isRegulationApplied('ccpa')) {
  // the user is subject to CCPA, do something
}
```

### navigate(button)

Simulate a user input by indicating to the SDK that the user has pressed a button on an input device like a keyboard or a TV remote control. This function is usually called when mapping TV remote control inputs to the Didomi SDK.

This function is only available if the TV mode of the SDK is enabled by adding the following `didomiConfig` to your page:

```javascript
window.didomiConfig = {
  mode: 'tv' // Enable TV mode
};
```

{% hint style="info" %}
`window.didomiConfig` must be set outside of any callback like `window.didomiOnReady` to be effective.
{% endhint %}

If no UI view is displayed from the Didomi SDK (notice, purposes, or vendors), this function has no effect and will log an error message that can be ignored.

**Parameters**

| **Name** | Type     | Description                                                                                      |
| -------- | -------- | ------------------------------------------------------------------------------------------------ |
| button   | `string` | The button that was pressed by the user. See below for the acceptable values for this parameter. |

The `button` parameter can take one of the following values:

| Value     | Description                                                                                                                                                                                                                                                              |
| --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `confirm` | When the user presses a confirmation button (like OK or Enter). This input validates the user choice when pressed on UI buttons like Agree or Disagree.                                                                                                                  |
| `cancel`  | When the user presses a cancellation button (like Return or Exit). This input cancels the current action and, usually, closes the current UI view.                                                                                                                       |
| `up`      | When the user presses a button to move up (like an Up arrow). This input moves the focus to the closest action button located above the current focused element. If no such input exists, the focus is moved to the last element of the current UI view.                 |
| `right`   | When the user presses a button to move right (like a Right arrow). This input moves the focus to the closest action button located to the right of the current focused element. If no such input exists, the focus is moved to the next element of the current UI view.  |
| `down`    | When the user presses a button to move down (like a Down arrow). This input moves the focus to the closest action button located below the current focused element. If no such input exists, the focus is moved to the first element of the current UI view.             |
| `left`    | When the user presses a button to move left (like a Left arrow). This input moves the focus to the closest action button located to the left of the current focused element. If no such input exists, the focus is moved to the previous element of the current UI view. |

**Returns**

No return value.

**Example**

```javascript
Didomi.navigate('down');
Didomi.navigate('confirm');
```

### notice.isVisible()

Check if the consent notice is currently displayed.

**Parameters**

No parameter.

**Returns**

`Boolean`

**Example**

```javascript
Didomi.notice.isVisible();
```

### preferences.show(view)

Show the preferences manager. This can be used to allow the user to update their consent choices after the notice has been closed. We suggest adding a link with this function call somewhere on your website.

**Parameters**

| Name | Type     | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| ---- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| view | `string` | <p>The view you want to open.</p><p>Possible options for GDPR: <code>information, purposes</code> and <code>vendors</code>. (<code>information</code> will only work if you <a href="../../consent-notice/preferences#information-screen">enabled the information view</a>).<br>For CCPA, the Do Not Sell view is always open.<br></p><p>This parameter is optional. If it is not provided, it will display the <code>purposes</code> view or the <code>information</code> view if information is enabled for GDPR.</p> |

**Returns**

Nothing

**Example**

```javascript
Didomi.preferences.show('purposes');
```

***

## User status

### addVendorStatusListener

#### Definition

Listens to the user’s status for a given vendor and returns a callback when the status changes.

#### Parameters

| Parameter | Type       | Description                                                                                                                                                                                   |
| --------- | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Vendor ID | `string`   | <ul><li>The ID of the vendor for which the changes will be tracked by the function.</li><li>This ID must be the Didomi API ID, with no prefixes (for example: <code>google</code>).</li></ul> |
| callback  | `function` | Callback that will be executed whenever changes are detected on the specified vendor.                                                                                                         |

#### **Returns**

Numeric value indicating the index position of the listener (zero-based indexing) in the list of registered listeners.

#### Example

```javascript
Didomi.addVendorStatusListener("google",(status) => console.log("Google: listener 1: status", status))
```

### clearUser()

Clear the user configuration details set via `setUser` or `window.didomiConfig.user` in a single-page application. This function does not clear the local user status (use `reset()` for that).

{% hint style="info" %}
If your website is not a single-page application, do not use this function and stop setting the user configuration details via `window.didomiConfig.user` on page load instead.
{% endhint %}

**Parameters**

No parameter.

**Returns**

`Promise<void>`

**Example**

```javascript
await Didomi.clearUser();
```

### getCurrentUserStatus()

#### Definition

Exposes the user status for the current regulation that applies.

#### Parameters

No parameters.

#### Returns

The user status containing the computed global status for Vendors and purposes:

* A vendor's global status is enabled, if and only if:
  * the vendor is enabled directly in the vendors layer in all legal basis
  * **AND** all its related purposes are enabled or essential.
* A purpose's global status is enabled in one of the two conditions:
  * the purpose is enabled for all the legal basis that it is configured for.
  * **OR** when the purpose is essential.

| Parameter       | Type     | Description                                                                                                                                                                                                                                                                                              |
| --------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| vendors         | `object` | <ul><li>Object that maps the ID of a vendor to an object representing its status.</li><li>Vendors with undefined user status are included in the response with <code>enabled: false.</code></li><li>Vendors with ONLY essential purposes are automatically set with <code>enabled: true</code></li></ul> |
| purposes        | `object` | <ul><li>Object that maps the ID of a purpose to an object representing its status.</li><li>Purposes with undefined user status are included in the response with <code>enabled: false.</code></li><li>Essential purposes are automatically set with <code>enabled: true</code></li></ul>                 |
| regulation      | `string` | <ul><li>Representation of the current regulation as a <code>Regulation</code> enum value, such as <code>GDPR</code>, <code>CCPA</code>, <code>CPRA</code>, or <code>NONE</code>.</li><li>Note that some regulations present as enum values are not available yet.</li></ul>                              |
| user\_id        | `string` | Didomi user id.                                                                                                                                                                                                                                                                                          |
| created         | `string` | User choices creation date.                                                                                                                                                                                                                                                                              |
| updated         | `string` | User choices update date.                                                                                                                                                                                                                                                                                |
| consent\_string | `string` | TCF consent as string                                                                                                                                                                                                                                                                                    |
| gpp\_string     | `string` | GPP string                                                                                                                                                                                                                                                                                               |
| addtl\_consent  | `string` | Additional consent.                                                                                                                                                                                                                                                                                      |

#### Example

```javascript
Didomi.getCurrentUserStatus();
```

### getRequiredPurposeIds()

Get the list of purpose IDs that are configured for the consent notice and that consent is collected for.

**Parameters**

No parameter.

**Returns**

An array of purpose IDs.

**Example**

```javascript
// Returns ['cookies']
Didomi.getRequiredPurposeIds();
```

### getRequiredVendors()

Get list of vendors that are configured for the consent notice for which consent is collected.

**Parameters**

<table><thead><tr><th width="229">Parameter</th><th width="176">Data Type</th><th>Description</th></tr></thead><tbody><tr><td>namespace</td><td><code>string</code></td><td>Filter the result by vendor class (e.g. <code>custom</code> | <code>didomi</code> | <code>iab</code> )</td></tr></tbody></table>

**Returns**

An array of vendor objects. Properties returned for each vendor object dependent on vendor class and declarations.

<table><thead><tr><th width="230">Property</th><th width="174">Data Type</th><th>Description</th></tr></thead><tbody><tr><td>didomiId</td><td><code>string</code></td><td>Didomi assigned vendor ID</td></tr><tr><td>featureIds</td><td><code>array</code></td><td>IAB features declared by the vendor</td></tr><tr><td>flexiblePurposeIds</td><td><code>array</code></td><td>Purpose IDs where vendor has registered flexible legal bases (consent or legitimate interest) with the IAB</td></tr><tr><td>id</td><td><code>number | string</code></td><td>IAB assigned ID | Didomi SDK ID</td></tr><tr><td>legIntPurposeIds</td><td><code>array</code></td><td>Opt-out purposes declared by a vendor (based on legitimate interest)</td></tr><tr><td>namespace</td><td><code>string</code></td><td>Defines the vendor class</td></tr><tr><td>purposeIds</td><td><code>array</code></td><td>Opt-in purposes declared by a custom vendor (requires end-user consent)</td></tr><tr><td>specialFeatureIds</td><td><code>array</code></td><td>IAB special features declared by a vendor</td></tr><tr><td>specialPurposeIds</td><td><code>array</code></td><td>IAB special purposes declared by a vendor</td></tr><tr><td>tmpDeletedDate</td><td><code>undefined | string</code></td><td>Vendor is considered deleted after this date/time</td></tr><tr><td>deviceStorageDisclosureUrl</td><td><code>string</code></td><td>URL disclosing details for web or app storage</td></tr><tr><td>cookieMaxAgeSeconds</td><td><code>number</code></td><td>The longest lifespan of a cookie (in seconds)</td></tr><tr><td>lang_urls</td><td><code>array</code></td><td>Url objects representing language, policy url and legitimate interest url</td></tr><tr><td>name</td><td><code>string</code></td><td>Name of the vendor</td></tr><tr><td>namespaces</td><td><code>object</code></td><td><p>Can contain:</p><ul><li>Namespace objects with additional IDs for the vendor</li><li><code>num</code>: Didomi Consent String encoding/decoding numeric ID</li></ul></td></tr><tr><td>policyUrl</td><td><code>string</code></td><td>URL of the vendor's privacy policy</td></tr><tr><td>type</td><td><code>string</code></td><td>Whether vendor is 1st_party or 3rd_party</td></tr><tr><td>usesNonCookieAccess</td><td><code>boolean</code></td><td><p>Indicates the vendor’s use of non-cookie storage and access to information already stored on an end-user’s device.</p><ul><li><strong>True</strong>: non-cookie access is used.</li><li><strong>False:</strong> non-cookie storage and access to information already stored on a end-user's device is not used</li></ul></td></tr></tbody></table>

**Example**

<details>

<summary><code>Didomi.getRequiredVendors();</code></summary>

```javascript
[
    {
        didomiId: "tomgdprv-1234Cm3G",
        id: "c:tomgdprv-MXUaCm3G",
        lang_urls: [],
        legIntPurposeIds: ["analytics_tracking"],
        name: "Custom Vendor Example",
        namespace: "custom",
        namespaces: {
            num: 12345
        },
        policyUrl: "https://demoprivacypolicy.com",
        purposeIds: ["advertising", "select_basic_ads", "create_ads_profile"],
        type: "3rd_party",
        usesNonCookieAccess: true
    }
]
```

</details>

### isUserStatusPartial()

This function assesses whether the user has made choices regarding all the vendors and data processing tasks specified by the regulation. It returns `true` if there are any vendors or data processing activities for which the user has yet to express a preference.

Requires SDK to be initialized.

**Parameters**

No parameter.

**Returns**

`Boolean`

\
The function returns `true` when the following conditions are all met:

1. A relevant regulation applies to the current user, meaning the regulation is not classified as `none`.
2. There is at least one vendor configured. Without any configured vendors, the function defaults to `false` since there are no statuses to evaluate.
3. There is a lack of user status for certain vendors or for specific purposes.

In all other scenarios, the function will return `false`.

For example, when the regulation is set to `none`, indicating that no specific regulation is applicable to the end-user, the function will yield `false`.

An important edge case to consider is when a new vendor is introduced to the system and their status has not yet been collected. In such instances, the function will return `true` until the user updates their preferences through the notice banner.

**Example**

```javascript
Didomi.isUserStatusPartial();
```

### openCurrentUserStatusTransaction

Create an instance of the `CurrentUserStatusTransaction` object.

This object provides mechanisms to stage updates to the user status regarding purposes and vendors, allowing for batch operations.

Updates made through its methods are queued and applied simultaneously to the user status only once the `commit` method of the returned object is called.

Additional notes:

* The status of vendors and purposes whose IDs are not specified through the methods provided by `CurrentUserStatusTransaction` are kept unchanged.
* Essential purposes are always set to enabled and can’t be updated by the methods provided by `CurrentUserStatusTransaction`.
* When the regulation applied for a user is `none`, the methods provided by `CurrentUserStatusTransaction` should not update the status of any vendor or purpose which will always remain as enabled. When the `commit` method is called it will return `false`.
* If the IDs that are passed through the methods provided by `CurrentUserStatusTransaction` don’t correspond to vendors or purposes required by the Notice Config, they will be ignored.

#### Parameters

No parameter.

**Returns**

An instance of the `CurrentUserStatusTransaction` object.

<table><thead><tr><th width="207">Method</th><th width="233">Parameters</th><th>Returns</th><th>Description</th></tr></thead><tbody><tr><td><code>enablePurpose</code></td><td><code>id</code> (<code>string</code>): ID of the purpose to be enabled.</td><td>Current <code>CurrentUserStatusTransaction</code> object.</td><td>Enable a single purpose based on its ID.</td></tr><tr><td><code>enablePurposes</code></td><td><code>ids</code> ([<code>string]</code>): IDs of the purposes to be enabled.</td><td>Current <code>CurrentUserStatusTransaction</code> object.</td><td>Enable multiple purposes based on their IDs.</td></tr><tr><td><code>disablePurpose</code></td><td><code>id</code> (<code>string</code>): ID of the purpose to be disabled.</td><td>Current <code>CurrentUserStatusTransaction</code> object.</td><td>Disable a single purpose based on its ID.</td></tr><tr><td><code>disablePurposes</code></td><td><code>ids</code> ([<code>string]</code>): IDs of the purposes to be disabled.</td><td>Current <code>CurrentUserStatusTransaction</code> object.</td><td>Disable multiple purposes based on their IDs.</td></tr><tr><td><code>enableVendor</code></td><td><code>id</code> (<code>string</code>): Didomi ID of the vendor to be enabled.</td><td>Current <code>CurrentUserStatusTransaction</code> object.</td><td>Enable a single vendor based on its Didomi ID.</td></tr><tr><td><code>enableVendors</code></td><td><code>ids</code> ([<code>string]</code>): Didomi IDs of the vendors to be enabled.</td><td>Current <code>CurrentUserStatusTransaction</code> object.</td><td>Enable multiple vendors based on their Didomi IDs.</td></tr><tr><td><code>disableVendor</code></td><td><code>id</code> (<code>string</code>): Didomi ID of the vendor to be disabled.</td><td>Current <code>CurrentUserStatusTransaction</code> object.</td><td>Disable a single vendor based on its Didomi ID.</td></tr><tr><td><code>disableVendors</code></td><td><code>ids</code> ([<code>string]</code>): Didomi IDs of the vendors to be disabled.</td><td>Current <code>CurrentUserStatusTransaction</code> object.</td><td>Disable multiple vendors based on their Didomi IDs.</td></tr><tr><td><code>commit</code></td><td>No parameters.</td><td><code>true</code> if user status has been updated, <code>false</code> otherwise.</td><td>Commit the changes that have been made through other methods.</td></tr></tbody></table>

#### Examples

```javascript
const transaction = didomi.openCurrentUserStatusTransaction();

// enable a purpose
transaction.enablePurpose("cookies");
// enable purposes
transaction.enablePurposes(["cookies", "analytics"]);
// disable a purpose
transaction.disablePurpose("analytics");
// disable purposes
transaction.disablePurposes(["cookies", "analytics"]);
// enable a vendor
transaction.enableVendor("vendor-1");
// enable vendors
transaction.enableVendors(["vendor-1", "vendor-2"]);
// disable a vendor
transaction.disableVendor("vendor-1");
// disable vendors
transaction.disableVendors(["vendor-1", "vendor-1"]);

// chain multiple calls
transaction.enablePurpose("cookies").disablePurpose("analytics");

// save user choices
transaction.commit();
```

#### Error handling

Invalid purposes or vendors will be ignored, errors will be logged in the browser's console

<pre class="language-javascript"><code class="lang-javascript">const transaction = Didomi.openCurrentUserStatusTransaction();
// enable purposes
transaction.enablePurposes(['cookies', 'invalid_ID']);
transaction.commit();

// Console output:
<strong>'Didomi SDK - disablePurpose ignored due to invalid purpose: invalid_ID'
</strong>true
</code></pre>

### reset()

Reset all the consent information for the current user and assign a new user ID. This will remove all cookies created by Didomi and will trigger re-collection of consent. The consent notice will be displayed again.

**Parameters**

No parameter.

**Returns**

Nothing

**Example**

```javascript
Didomi.reset();
```

### setUser(userConfiguration)

Update the user configuration details in a single-page application. You can provide the user configuration options as part of the `userConfiguration` parameter.

{% hint style="info" %}
If your website is not a single-page application, do not call this function and set the user configuration details via `window.didomiConfig.user` on page load instead.
{% endhint %}

{% hint style="info" %}
The `setUser` function will update all the provided properties and set the others to `undefined`. If a property is omitted, it will be set to `undefined`.
{% endhint %}

**Parameters**

| Name              | Type     | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| ----------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| userConfiguration | `object` | <p>An object containing any of the following properties:<br><br><code>organizationUserId</code>: Organization User ID to associate with the user<br><code>organizationUserIdAuthAlgorithm</code>: Algorithm used for computing the digest<br><code>organizationUserIdAuthSid</code>: ID of the secret used for computing the digest<br><code>organizationUserIdAuthSalt</code>: Salt used for computing the digest<br><code>organizationUserIdAuthDigest</code>: Digest of the organization user ID and secret<br><code>organizationUserIdExp</code>: Unix timestamp<br><code>organizationUserIdIv</code>: If encryption is used and an IV was used for encrypting the message</p> |

**Returns**

Nothing

**Example**

```javascript
Didomi.setUser({ organizationUserId: 'organizationUserID' });
```

### setUserAgreeToAll()

Report that the user has enabled consents and legitimate interests for all purposes and vendors configured for your website.

This function will log the user choice on our platform and close the notice.

Consent statuses for essential purposes are not stored.\
[Read our detailed section](https://gitlab.com/didomi/developers-documentation/-/blob/main/docs/cmp/web-sdk/reference/broken-reference/README.md) to see how essential purposes behave and how to configure them.

Please read [our article](https://support.didomi.io/analytics-with-a-custom-setup) on what to expect from your analytics when setting a custom behavior for your consent notice.

**Parameters**

No parameter.

**Returns**

Nothing

**Example**

```javascript
Didomi.setUserAgreeToAll();
```

### setUserDisagreeToAll()

Report that the user has disabled consents and legitimate interests for all purposes and vendors configured for your website.

This function will log the user choice on our platform and close the notice.

Consent statuses for essential purposes are not stored.\
[Read our detailed section](https://gitlab.com/didomi/developers-documentation/-/blob/main/docs/cmp/web-sdk/reference/broken-reference/README.md) to see how essential purposes behave and how to configure them.

Please read [our article](https://support.didomi.io/analytics-with-a-custom-setup) on what to expect from your analytics when setting a custom behavior for your consent notice.

**Parameters**

No parameter.

**Returns**

Nothing

**Example**

```javascript
Didomi.setUserDisagreeToAll();
```

### setCurrentUserStatus(parameters)

#### Definition

Set the user status for purposes and vendors. This function will trigger events and API calls every time it is called (and the user status changes) so make sure to push all user choices at once and not one by one.

Please read [our article](https://support.didomi.io/analytics-with-a-custom-setup) on what to expect from your analytics when setting a custom behavior for your consent notice.

#### Parameters

Add the desired global status for each vendor and each purpose:

* the vendor status specified in this function will be reflected on the vendor’s layer.
  * vendor enabled : true → means the vendor is enabled in all the legal basis that this vendor uses.
  * vendor enabled : false → means the vendor is disabled in all the legal basis that this vendor uses
* the purposes status specified in this function will be reflected on the preferences layer.
  * purpose enabled : true → means the purpose is enabled in all the legal basis in which it’s defined.
  * purpose enabled : false → means the purpose is disabled in all the legal basis in which it’s defined.

#### Returns

`boolean`

`true` if the user's choices have changed (i.e. the user had made different choices before this function got called).

#### Example

```javascript
Didomi.setCurrentUserStatus({
  purposes: {
    purpose1: {
      id: "purpose1",
      enabled: true,
    },
    purpose2: {
      id: "purpose2",
      enabled: false
    }
  },
  vendors: {
    vendor1: {
      id: "vendor1",
      enabled: true
    },
    vendor2: {
      id: "vendor2",
      enabled: false
    }
  }
});
```

### setWidgetLocale()

{% hint style="info" %}
This function is only supported by [Privacy widgets](https://developers.didomi.io/api-and-platform/widgets/privacy-widgets).
{% endhint %}

#### **Definition**

Set the language for a widget.

#### **Parameters**

| Name      | Type   | Description                                                                                                                                                                                   |
| --------- | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Widget ID | String | The identifier for the widget.                                                                                                                                                                |
| Locale    | String | The language code for the display language. View the list of available languages [here](https://chat.openai.com/g/g-q7kFlQPHr-documentation-reviewer/c/0544af67-ff28-4d60-be4b-7e5741bd4c55). |

#### Example

<pre class="language-javascript"><code class="lang-javascript"><strong>const widget = await Didomi.getContainerById("WIDGET_ID")
</strong>
widget.setWidgetLocale('fr')
</code></pre>

### shouldUserStatusBeCollected()

Determine if user status (consent) should be collected for the visitor. Returns `true` if user status is required for the current user and one of the following two conditions is met:

* User status has never been collected for this visitor yet
* New user status should be collected (as new vendors have been added) AND the configured number of days before recollecting consent has been exceeded
* The [ignoreConsentBefore](https://developers.didomi.io/cmp/web-sdk/consent-notice/notice/behavior#recollect-consent-after-a-certain-date) flag has been set with a date that applies to force consent renewal

If none of these conditions is met, the function returns `false`. This function is mainly present to allow you to know when to display your own notice if you have disabled our standard notice.

**Parameters**

No parameter.

**Returns**

`Boolean`

**Example**

```javascript
Didomi.shouldUserStatusBeCollected();
```

### syncUser()

Update the local user status from the server in a single-page application if the server has a more recent user status than the local one.

{% hint style="info" %}
If your website is not a single-page application, do not call this function as syncing will be done automatically when the user configuration details are set via `window.didomiConfig.user` on page load.
{% endhint %}

{% hint style="info" %}
The synchronization only runs if the following conditions are met: synchronization is enabled in the configuration, an organization user ID has been provided for the user, the user is not a bot, and the sync frequency has not been exceeded.
{% endhint %}

**Parameters**

No parameter.

**Returns**

A promise that resolves when the user status has been synced with the server:

```javascript
Promise<SyncReadyEvent>
```

A `SyncReadyEvent` is provided as the return value of the function with the following properties:

| Property         | Type                  | Description                                                                                                                                                                                          |
| ---------------- | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| statusApplied    | `boolean`             | Indicates if the user status has been applied locally from the remote Didomi backend. `true` if the user status was applied from the remote, `false` otherwise.                                      |
| syncAcknowledged | `Function`            | Callback that can be used to communicate to the Didomi servers that the synchronization has been communicated to the user. Returns `true` if the API event was successfully sent, `false` otherwise. |
| syncError        | `undefined \| string` | An error message if the sync failed                                                                                                                                                                  |

**Example 1 - Simple sync**

```javascript
await Didomi.syncUser();
```

**Example 2 - Reassurance notice**

```javascript
const syncResult = await Didomi.syncUser();

if (syncResult.statusApplied) {
    // The user status actually changed from syncing
    
    // Show your reassurance notice
    
    // Report the reassurance notice as shown
    syncResult.syncAcknowledged();
}
```

### getRemoteConsentsFromAPI()

Fetch the current user’s remote consents from the Consents API via the Web SDK, instead of calling the HTTP endpoint directly. Typical use case: retrieve an existing consent state to condition UI (for example, hide a widget if an opt-in already exists).

{% hint style="info" %}
Prerequisite: you must create a Consent Token for the end-user first, this method only works when the SDK holds a valid consent token. See Consents & Preferences → Tokens for how to create a token.
{% endhint %}

**Returns**

```
Promise<RemoteConsents | null>
```

* Resolves with the normalized remote consents payload (or `null` when the user is not authenticated with a consent token).
* Also emits SDK events to signal loading/auth status.

**Limitations**

* Consent Token required. This method only works when the SDK has a valid Consent Token; it does not accept `org_id` or `org_user_id` parameters directly. See [Tokens docs](https://developers.didomi.io/api-and-platform/consents/tokens) for token creation flows.
* Subset of Consents API parameters. Only the `$merge_users` behavior is exposed via the `mergeUsers` option. Other Consents API query parameters are not supported here, use the HTTP API directly if you need full flexibility. See Consents & Preferences → Users to learn about the `/consents/users` endpoint.

**Notes**

* A `404` from the Consents API when calling this method does not imply an invalid token, but rather that no user exists yet for the given `organization_user_id`. Authentication will still be marked as `true`.
* This method always calls the API with `mergeUsers = false`, and this behavior

  cannot currently be changed via parameters.
* On success, the SDK normalizes the consents object and updates internal state; an “authenticated” event is emitted.

**Example 1 - Basic fetch**

```javascript
window.didomiOnReady = window.didomiOnReady || [];

window.didomiOnReady.push(async function (Didomi) {
  // Assumes you already created and set a Consent Token for this user.
  const data = await Didomi.getRemoteConsentsFromAPI();
  
  if (data?.consents) {
    console.log('Remote consents:', data.consents);
  }
});
```

**Example 2 - Conditionally hide a widget if opt-in already exists**

```javascript
window.didomiOnReady = window.didomiOnReady || [];

window.didomiOnReady.push(async function (Didomi) {
  const data = await Didomi.getRemoteConsentsFromAPI();
  const hasMarketingOptIn = !!data?.consents?.purposes?.marketing?.enabled;

  if (hasMarketingOptIn) {
    // End-user already opted in → don't render the signup widget.
    document.querySelector('#marketing-widget')?.remove();
  } else {
    // No opt-in yet → show your widget.
    document.querySelector('#marketing-widget')?.classList.remove('hidden');
  }
});
```

***

## GDPR

### \_\_tcfapi(command, version, callback, parameter)

Didomi is fully compliant with the CMP API from the [IAB Transparency and Consent framework version 2](https://github.com/InteractiveAdvertisingBureau/GDPR-Transparency-and-Consent-Framework/blob/master/TCFv2/IAB%20Tech%20Lab%20-%20CMP%20API%20v2.md#how-does-the-cmp-provide-the-api).\
We expose a `__tcfapi` function and listen to `postMessage` events as per the specification.

Example (getting the IAB consent string):

```javascript
__tcfapi('getTCData', null, function (result) {
  // The IAB consent string is available in the `tcString` property of the object
  console.log(result.tcString);
});
```

[Read more in the IAB documentation](https://github.com/InteractiveAdvertisingBureau/GDPR-Transparency-and-Consent-Framework/blob/master/TCFv2/IAB%20Tech%20Lab%20-%20CMP%20API%20v2.md#how-does-the-cmp-provide-the-api)
