Following Google instructions I am setting consent on a website I am working on.
I am able to set gtag()
consent through GTM and everything else, I was wondering: how do I get back the values that user set in gtag('consent')
? (such as default|update
and ad_user_data
,functionality_storage
, etc.)
The Google documentation explains that gtag() has a gtag('get')
option, but gtag('consent')
seems to be a pletely different option on which gtag('get')
does not work, and I cannot retrieve values set.
Following Google instructions I am setting consent on a website I am working on.
I am able to set gtag()
consent through GTM and everything else, I was wondering: how do I get back the values that user set in gtag('consent')
? (such as default|update
and ad_user_data
,functionality_storage
, etc.)
The Google documentation explains that gtag() has a gtag('get')
option, but gtag('consent')
seems to be a pletely different option on which gtag('get')
does not work, and I cannot retrieve values set.
- 1 Please see How to Ask, then revise your title to ask a clear, specific question. Don't add tags (especially abbreviations). Also, never link "here". – isherwood Commented Feb 28, 2024 at 15:10
3 Answers
Reset to default 5It is possible to use this function:
window.google_tag_data.ics.getConsentState("analytics_storage");
0 indicates no consent (denied), and 1 signifies consent has been granted.
Im not an expert regarding this subject but i found something that worked for me:
dataLayer
Is a variable that seems to include all internal data of gtag. Therefore what you can do:
Object.values(dataLayer).filter(a=> typeof a === 'object' && a?.[0] === 'consent')
Should return all consents. This should return all consent objects from dataLayer regarding consent.
Since it stores the history with all changes to datalayer personally I prefer to have an object that simply represents the current state of consent:
//merges an array of objects into a single object, where properties from later objects overwrite those from earlier ones
function mergeObjects(array) {
return array.reduce((acc, obj) => ({ ...acc, ...obj }), {});
}
const consentHistory = Object.values(dataLayer).filter(a=> typeof a === 'object' && a[0] === 'consent');
mergeObjects(consentHistory.map(a=>a?.[2]||{}));
This code snippet returns on my end:
{
"ad_storage": "granted",
"ad_user_data": "granted",
"ad_personalization": "granted",
"analytics_storage": "granted",
"functionality_storage": "granted",
"personalization_storage": "granted",
"security_storage": "granted"
}
Notice I didn't test it in detail.
If you have GTM then window.google_tag_data.ics.entries contains information on the current consent states.
A hacky method is to intercept all pushes to the data layer and monitor for consent mands. To get it right is a bit plex as you need to merge the data in the mands and update override defaults. It is also not aware of all consent changes within GTM.