Unlock Granular Consent Data: Extracting Specific Values from Your GTM DataLayer
Effortlessly create GTM variables to track individual user consent choices directly from your consents array.
Tracking user consent accurately is crucial for compliance and personalized experiences. When your Consent Management Platform (CMP) pushes detailed consent information into the Google Tag Manager (GTM) dataLayer, you often need to access specific consent choices individually. Your dataLayer.push contains a consents array, where each object represents a different consent category with its status. This guide details how to create five distinct GTM variables, each capturing the boolean consent value (true or false) for a specific consent type from your array.
Key Insights for Extracting Consent Values
- Custom JavaScript Variables are Essential: Accessing specific values within an array of objects in the dataLayer requires more than a standard Data Layer Variable. Custom JavaScript variables provide the necessary logic to parse the array and find the correct data.
- Match by Name, Not Index: Relying on the array index (e.g.,
consents.0.consent) is risky, as the order might change. The robust method involves searching the array for an object whosenameproperty matches the desired consent category (e.g., "Essential%20cookies"). - Event Context Matters: Ensure your variables retrieve data specifically from the
grvupdateevent push, as this guarantees you're accessing the latest consent update information provided by your CMP.
Understanding the Challenge: Accessing Nested Array Data
Why Standard Data Layer Variables Fall Short
The standard "Data Layer Variable" type in GTM is perfect for accessing simple key-value pairs directly pushed to the dataLayer (e.g., pageType, userId). However, your consents data is structured as an array of objects:
consents: [
{id: 1, name: "Essential%20cookies", isConsentable: false, consent: true},
{id: 2, name: "Functional%20cookies", isConsentable: true, consent: true},
// ... and so on
]
To get the consent value for "Functional%20cookies", you can't simply use a Data Layer Variable name like consents.Functional%20cookies.consent. You also shouldn't rely on consents.1.consent because the order of items in the consents array might not be consistent across different page loads or user sessions.
The Solution: Custom JavaScript Variables
Custom JavaScript variables allow you to write code that interacts with the window.dataLayer object directly. This provides the flexibility needed to:
- Iterate through the
dataLayerhistory to find the specificgrvupdateevent push. - Access the
consentsarray within that event object. - Search (find) the object within the array whose
nameproperty matches the specific category you're interested in (e.g., "Statistical%20cookies"). - Return the corresponding
consentproperty value (trueorfalse).
This method is robust against changes in array order and ensures you retrieve the correct consent status based on the category name.
Step-by-Step Guide: Creating Consent Variables in GTM
Creating the Five Custom JavaScript Variables
Follow these steps within your Google Tag Manager container to create a variable for each consent type:
- Navigate to the "Variables" section in your GTM workspace.
- Under "User-Defined Variables," click "New."
- Choose "Custom JavaScript" as the Variable Type.
- Give your variable a descriptive name (e.g.,
JSV - Consent - Essential). - Paste the appropriate JavaScript code (provided below) into the Custom JavaScript field.
- Save the variable.
- Repeat steps 2-6 for each of the five consent categories, using the corresponding code snippet.
Custom JavaScript variables provide the power to parse complex dataLayer structures.
JavaScript Code Snippets
Use the following base code structure. For each variable, replace the value of the targetName variable with the specific URL-encoded name from your dataLayer push.
Base Code Structure:
function() {
// Access the entire dataLayer array
var dataLayer = window.dataLayer || [];
var targetEventObject = null;
// Find the most recent 'grvupdate' event object containing the 'consents' array
// Iterate backwards through the dataLayer for efficiency
for (var i = dataLayer.length - 1; i >= 0; i--) {
// Check for the specific event name and if 'consents' exists and is an array
if (dataLayer[i] && dataLayer[i].event === 'grvupdate' && Array.isArray(dataLayer[i].consents)) {
targetEventObject = dataLayer[i];
break; // Found the latest relevant event, stop searching
}
}
// If the specific event or the 'consents' array wasn't found, return undefined
if (!targetEventObject || !targetEventObject.consents) {
return undefined; // Indicate that the value couldn't be determined
}
// Get the consents array from the found event object
var consentsArray = targetEventObject.consents;
// *** IMPORTANT: Set the target name for THIS specific variable below ***
var targetName = "REPLACE_WITH_URL_ENCODED_NAME"; // e.g., "Essential%20cookies"
// Find the object within the consents array that matches the target name
var foundConsent = consentsArray.find(function(consentObj) {
// Directly compare the URL-encoded name from the dataLayer
return consentObj && consentObj.name === targetName;
});
// Return the boolean 'consent' value if the object was found, otherwise return undefined
return foundConsent ? foundConsent.consent : undefined;
}
Specific Implementations:
- Variable Name:
JSV - Consent - Essential
Code: Use the base code, setvar targetName = "Essential%20cookies"; - Variable Name:
JSV - Consent - Functional
Code: Use the base code, setvar targetName = "Functional%20cookies"; - Variable Name:
JSV - Consent - Statistical
Code: Use the base code, setvar targetName = "Statistical%20cookies"; - Variable Name:
JSV - Consent - Marketing Advertising
Code: Use the base code, setvar targetName = "Marketing%20%26%20advertising%20cookies"; - Variable Name:
JSV - Consent - Uncategorised
Code: Use the base code, setvar targetName = "Uncategorised%20Cookies";
Important Note: The code returns undefined if the grvupdate event isn't found or if a specific consent name doesn't exist within the consents array for that event. This distinction is useful for debugging compared to defaulting to false, which could imply consent was actively denied.
Visualizing the Data Extraction Process
Mindmap of Data Flow
This mindmap illustrates how the Custom JavaScript variable navigates the dataLayer to extract the desired consent value:
The Custom JavaScript variable effectively searches the consents array within the correct event push, identifies the object matching the specified targetName, and returns its consent status.
Comparing Data Extraction Methods
Why Custom JavaScript Wins
While using indexed Data Layer Variables (e.g., consents.0.consent) might seem simpler, it lacks robustness. This radar chart compares the Custom JavaScript approach with the index-based Data Layer Variable method across key attributes:
As the chart illustrates, the Custom JavaScript method significantly outperforms the index-based approach in terms of robustness, reliability, and flexibility, especially when dealing with potentially dynamic data structures like the consents array. While slightly more complex to set up initially, the long-term benefits in accuracy and maintainability make it the preferred solution.
Leveraging Your New Variables
Using Consent Variables in Triggers and Tags
Once created, these five variables (JSV - Consent - Essential, JSV - Consent - Functional, etc.) become powerful tools in your GTM setup:
- Conditional Tag Firing: Use the variables in trigger conditions. For example, configure your marketing tags (like a Facebook Pixel or Google Ads conversion tag) to fire only when
JSV - Consent - Marketing Advertisingequalstrue. - Trigger Exceptions: Prevent tags from firing if consent is denied. Add an exception trigger to sensitive tags that fires when the relevant consent variable equals
false. - Passing Data to Tags: Include the variable values within your tags to send consent status to analytics platforms or advertising networks, potentially enabling features like Google's Consent Mode.
- Debugging: Use GTM's Preview mode to check the values returned by these variables after the
grvupdateevent fires, ensuring your logic works correctly.
Video Explainer: Working with Data Layer Variables
Understanding how GTM interacts with the dataLayer is fundamental. While this video discusses standard Data Layer Variables, the principles of accessing data pushed to the dataLayer are relevant context for creating Custom JavaScript variables as well.
Learn how GTM variables pull data from the dataLayer.
Summary Table: Consent Variables
This table provides a quick overview of the five Custom JavaScript variables you'll create:
| Variable Name (Suggested) | Target Consent Name (URL Encoded) | Purpose | Returns |
|---|---|---|---|
JSV - Consent - Essential |
Essential%20cookies |
Retrieves consent status for essential cookies. | true, false, or undefined |
JSV - Consent - Functional |
Functional%20cookies |
Retrieves consent status for functional cookies. | true, false, or undefined |
JSV - Consent - Statistical |
Statistical%20cookies |
Retrieves consent status for statistical cookies. | true, false, or undefined |
JSV - Consent - Marketing Advertising |
Marketing%20%26%20advertising%20cookies |
Retrieves consent status for marketing & advertising cookies. | true, false, or undefined |
JSV - Consent - Uncategorised |
Uncategorised%20Cookies |
Retrieves consent status for uncategorised cookies. | true, false, or undefined |
Frequently Asked Questions (FAQ)
Q: Why use Custom JavaScript instead of multiple Data Layer Variables with indexes?
Using indexes (e.g., consents.0.consent, consents.1.consent) relies on the order of items in the consents array remaining constant. If the order changes for any reason (e.g., updates to the CMP, different user interactions), your variables will pull the wrong consent values. Custom JavaScript variables that find the consent object by its unique name are far more robust and reliable, as they don't depend on array order.
Q: What happens if the `grvupdate` event doesn't fire or the `consents` array is missing?
The provided JavaScript code is designed to handle these cases gracefully. It first searches the dataLayer history for the most recent `grvupdate` event that contains a valid `consents` array. If no such event is found, or if the found event object doesn't contain the `consents` array, the function returns `undefined`. Similarly, if the array is present but the specific `name` being searched for isn't found within it, the function also returns `undefined`. This helps distinguish between "consent denied" (`false`) and "consent status unknown/not found" (`undefined`).
Q: Do I need to decode the URL-encoded names like "Essential%20cookies"?
The provided code snippets match against the URL-encoded names exactly as they appear in your `dataLayer.push` example (e.g., `"Essential%20cookies"`). This is the simplest and most direct way to ensure a match. While you could technically decode the names in the JavaScript using `decodeURIComponent(consentObj.name)` and compare against the decoded string (e.g., `"Essential cookies"`), it adds an extra step. Matching the encoded string directly is perfectly fine as long as the encoding in the dataLayer is consistent.
Q: How can I test if these variables are working correctly?
Use Google Tag Manager's Preview mode. Open your website in Preview mode, interact with your consent banner to trigger the `grvupdate` event (or simulate the `dataLayer.push` via the browser console if needed). Then, in the Preview mode debug panel, navigate to the "Variables" tab *after* the `grvupdate` event has fired. You should see your newly created Custom JavaScript variables (e.g., `JSV - Consent - Functional`) listed along with their returned values (`true`, `false`, or `undefined`). Verify these values match the actual consent choices made.
Recommended Further Exploration
- How can I configure Google Consent Mode v2 using Google Tag Manager and these variables?
- What are the best practices for naming variables and triggers in Google Tag Manager for maintainability?
- How can I effectively debug dataLayer issues using the Google Tag Manager Preview mode?
- Can I create GTM triggers based on combinations of these different consent variables?
References
Last updated April 29, 2025