How to use the CMP API (__tcfapi)

CookieHub implements the standard __tcfapi function defined by IAB. This API allows developers to retrieve consent information or listen for consent changes.

Common commands

  • ping – Checks if the CMP is loaded and GDPR applies
  • getTCData – Retrieves the current consent data, including the TC string
  • addEventListener – Subscribes to updates when consent status changes

Example:

__tcfapi('getTCData', 2, (tcData, success) => {
  if (success) {
    console.log('TC String:', tcData.tcString);
  }
});

Here are some practical examples for interacting with the CMP API:

Ping the CMP

__tcfapi('ping', 2, (pingReturn) => {
  console.log('CMP loaded:', pingReturn.cmpLoaded);
});

Get current consent data

__tcfapi('getTCData', 2, (tcData, success) => {
  if (success) {
    console.log('Purposes consented:', tcData.purpose.consents);
  }
});

Subscribe to consent changes

__tcfapi('addEventListener', 2, (tcData, success) => {
  if (success) {
    console.log('Consent updated:', tcData);
  }
});

These methods allow advanced integrations without needing to decode the TC string manually.