Skip to content

Instantly share code, notes, and snippets.

@shadybones
Last active January 29, 2024 08:59
Show Gist options
  • Save shadybones/71617252fd8814d1b9f9a6114030f63a to your computer and use it in GitHub Desktop.
Save shadybones/71617252fd8814d1b9f9a6114030f63a to your computer and use it in GitHub Desktop.
Partial integration between the TrustArc Consent Manager API and Google Tag Manager. This code allows for GTM event-based tag firing solution.
var __dispatched__ = {}; //Map of previously dispatched preference levels
/* First step is to register with the CM API to recieve callbacks when a preference update occurs
You must wait for the CM API (PrivacyManagerAPI object) to exist on the page before registering
*/
var __i__ = self.postMessage && setInterval(function(){
if(self.PrivacyManagerAPI && __i__){
var apiObject = { PrivacyManagerAPI:
{ action:"getConsentDecision",
timestamp: new Date().getTime(),
self: self.location.host }};
self.top.postMessage(JSON.stringify(apiObject),"*");
__i__ = clearInterval(__i__);
}},50);
/*
Callbacks will occur in the form of a PostMessage event.
This code listens for the appropriately formatted PostMessage event,
get's the new consent decision, and pushes the events into the GTM framework.
Once the event is submitted, that consent decision is marked in the 'dispatched' map so it does not occur more than once.
*/
self.addEventListener("message", function(e, d){
try{
if(e.data && (d= JSON.parse(e.data)) &&
(d = d.PrivacyManagerAPI) && d.capabilities && d.action=="getConsentDecision"){
var newDecision = self.PrivacyManagerAPI.callApi("getGDPRConsentDecision",self.location.host).consentDecision;
newDecision && newDecision.forEach(function(label){
if(!__dispatched__[label]){
self.dataLayer && self.dataLayer.push({"event":"GDPR Pref Allows "+label});
__dispatched__[label] = 1;
}
});
}
}catch(xx){/** not a cm api message **/}
});
@stefanatcroud
Copy link

Yes, thank you for sharing that!

@stefanatcroud, that's a great way to push the Google Consent Mode updates. I am probably late with the comment but I will leave it here in case it helps others: If you are using GTM, there's also the option to use the public template for Google Consent Mode integration.

https://tagmanager.google.com/gallery/#/owners/trustarc/templates/trustarc-cmp-gcm-template

Thanks, Felipe.

Worth mentioning that TrustArc appear to be integrating directly with CoMo for their hardcoded script as well now. You're still responsible for setting up the CoMo default with a gtag script on site, just like we do with OneTrust and CookieBot. I have a call with a TrustArc rep this week to discuss because they haven't documented this change (yet!).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment