Hi, here is a solution to use HubSpot’s new cookie consent banners (Consent banner API - HubSpot docs) with Google Tag Managers consent settings API (Set up consent mode on websites | Tag Platform | Google for Developers) for much easier category consent triggering in GTM.
First, enable Consent Overview in your container. Go To your GTM account, navigate to Admin → Container Settings, and tick the Enable consent overview. With this, you will be able to test event consent states in the preview testing of your GTM account.
Second, add this code for the Initialization of GTM Consent Mode above your GTM script. This code checks if a saved consent mode exists in localStorage and sets the default consent mode for GTM accordingly. We check if savedConsent exists, if it does, an immediately-invoked function expression is used to try parsing the saved consent and validate its properties. If the parsing or validation fails, the defaultConsent is returned, and if savedConsent doesn’t exist, the defaultConsent is used directly.
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
var savedConsent = localStorage.getItem('consentMode');
var defaultConsent = {
'ad_storage': 'denied',
'analytics_storage': 'denied',
'functionality_storage': 'denied',
};
var consentMode = savedConsent ?
(function() {
try {
var parsedConsent = JSON.parse(savedConsent);
return (parsedConsent.ad_storage && parsedConsent.analytics_storage && parsedConsent.functionality_storage) ?
parsedConsent : defaultConsent;
} catch (e) {
return defaultConsent;
}
})() :
defaultConsent;
gtag('consent', 'default', consentMode);
And then you add this HubSpot Cookie Consent Listener after your GTM script which waits for any changes in user consent. When a change is detected, it updates the GTM consent mode and saves the updated mode to localStorage.
var _hsp = window._hsp = window._hsp || [];
_hsp.push(['addPrivacyConsentListener', function(consent) {
var consentMode = {
analytics_storage: consent.categories.analytics ? 'granted' : 'denied',
ad_storage: consent.categories.advertisement ? 'granted' : 'denied',
functionality_storage: consent.categories.functionality ? 'granted' : 'denied'
};
gtag('consent', 'update', consentMode);
localStorage.setItem('consentMode', JSON.stringify(consentMode));
}]);
So now, inside GTM, on a tag level I can control which tags are fired when: