Links

Working with iframes

iframes on your website can use the commands provided by the CMP API. They can do this by making calls to the parent's (or ancestor's) frame that the CMP is loaded on, sending the commands as a message with the postMessage() function.
The frame to make the call to can be determined by the ancestor by looking for a.frames["__tcfapiLocator"] child.

Send a command

The message to send should have the below form where the __tcfapiCall object holds the information about the command to execute. command and parameter are the same as the parameters passed to the __tcfapi() function, and callId est un ID unique à déterminer.
__tcfapiCall format
Example
{
__tcfapiCall: {
command: *command*, // name of the command to execute
version: 2, // version of the TCF specification
parameter: *parameter*, // parameter to be passed to the command function
callId: *uniqueId* // unique call ID
}
}
this.callId = this.callId || 0;
var message = {
__tcfapiCall: {
command: 'getTCData',
version: 2,
parameter: [1,2,53],
callId: ++this.callId
}
};
window.top.postMessage(message, '*');

Retrieve the command result

Before sending messages, the iframe must define a JavaScript function to execute when a message is sent back. To do this, it must add a listener for the event message with the window.addEventListener() function. By doing this, it will be able to receive and process the command result in __tcfapiReturn.
Thewindow.addEventListener()function is different from the addEventListener command, which is included in the CMP API.
Example
function processMessage(event) {
if (event && event.data && event.data.__tcfapiReturn && event.data.__tcfapiReturn.success) {
console.log(event.data.__tcfapiReturn.returnValue);
}
}
window.addEventListener('message', processMessage);
When a command is sent, the returned message (event.data) holds the __tcfapiReturn object with the command result. returnValue and success are the same as the parameters passed to the callback of the __tcfapi() function, and callId is the ID from the origin call (__tcfapiCall).
__tcfapiReturn format
Example
{
__tcfapiReturn: {
returnValue: *returnValue*, // result of the command
success: *boolean*, // true if the call to the command was successful
callId: *uniqueId* // call ID sent in the __tcfapiCall
}
}
function processMessage(event) {
if (event && event.data && event.data.__tcfapiReturn && event.data.__tcfapiReturn.success) {
var tcData = event.data.__tcfapiReturn.returnValue;
if (!tcData.gdprApplies) {
console.log("GDPR doesn't apply to user");
}
console.log("TC String : ", tcData.tcString);
}
}
window.addEventListener('message', processMessage);
this.callId = this.callId || 0;
var message = {
__tcfapiCall: {
command: 'getTCData',
version: 2,
parameter: [1, 2, 53],
callId: ++this.callId
}
};
window.top.postMessage(message, '*');