Support pour les iframes
Les iframes intégrées sur votre site peuvent utiliser les commandes fournies par la CMP API.
Pour cela, elles doivent effectuer des appels à la "frame" parente (ou à une frame ancêtre) sur laquelle la CMP est chargée, en envoyant les commandes sous forme de message grâce à la fonction
postMessage()
.La frame vers laquelle effectuer l'appel peut être déterminée par l'ancêtre en cherchant la frame enfant
.frames["__tcfapiLocator"]
.Le message à envoyer doit avoir le format ci-dessous où l'objet
__tcfapiCall
contient les informations de la commande à exécuter.
command
et parameter
sont identiques aux paramètres passés à la fonction __tcfapi()
, et callId
est un ID unique à déterminer.Format __tcfapiCall
Exemple
{
__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, '*');
Avant d'envoyer des messages, l'iframe doit mettre en place une fonction JavaScript à exécuter lorsqu'un message est renvoyé en retour. Pour cela, elle doit tracer l'évènement message avec la fonction
window.addEventListener()
.
De cette façon, elle récupèrera et pourra traiter le résultat de la commande contenu dans __tcfapiReturn
.La fonction
window.addEventListener()
est différente de la commande addEventListener, qui est propre à la CMP API.Exemple
function processMessage(event) {
if (event && event.data && event.data.__tcfapiReturn && event.data.__tcfapiReturn.success) {
console.log(event.data.__tcfapiReturn.returnValue);
}
}
window.addEventListener('message', processMessage);
Lorsqu'une commande est envoyée, le message renvoyé en retour (event.data) contient l'objet
__tcfapiReturn
avec le résultat de la commande.
returnValue
et success
sont identiques aux paramètres passés à la callback de la fonction __tcfapi()
, et callId
correspond à l'ID de l'appel d'origine (__tcfapiCall
).Format __tcfapiReturn
Exemple
{
__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, '*');
Dernière mise à jour 2yr ago