Ask me anything
Ithy Logo
Sign in to save

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.

extract-gtm-consent-array-variables-3y2kl4vq

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 whose name property matches the desired consent category (e.g., "Essential%20cookies").
  • Event Context Matters: Ensure your variables retrieve data specifically from the grvupdate event 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:

  1. Iterate through the dataLayer history to find the specific grvupdate event push.
  2. Access the consents array within that event object.
  3. Search (find) the object within the array whose name property matches the specific category you're interested in (e.g., "Statistical%20cookies").
  4. Return the corresponding consent property value (true or false).

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:

  1. Navigate to the "Variables" section in your GTM workspace.
  2. Under "User-Defined Variables," click "New."
  3. Choose "Custom JavaScript" as the Variable Type.
  4. Give your variable a descriptive name (e.g., JSV - Consent - Essential).
  5. Paste the appropriate JavaScript code (provided below) into the Custom JavaScript field.
  6. Save the variable.
  7. Repeat steps 2-6 for each of the five consent categories, using the corresponding code snippet.
Laptop showing JavaScript code

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:

  1. Variable Name: JSV - Consent - Essential
    Code: Use the base code, set var targetName = "Essential%20cookies";
  2. Variable Name: JSV - Consent - Functional
    Code: Use the base code, set var targetName = "Functional%20cookies";
  3. Variable Name: JSV - Consent - Statistical
    Code: Use the base code, set var targetName = "Statistical%20cookies";
  4. Variable Name: JSV - Consent - Marketing Advertising
    Code: Use the base code, set var targetName = "Marketing%20%26%20advertising%20cookies";
  5. Variable Name: JSV - Consent - Uncategorised
    Code: Use the base code, set var 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:

mindmap root["DataLayer Push (grvupdate Event)"] id1["event: grvupdate"] id2["consents: [...] (Array)"] id2_1["{ name: Essential%20cookies, consent: true }"] id2_1_1["Target Name Match?"] id2_1_1_1["Yes -> Return 'consent' value (true)"] id2_2["{ name: Functional%20cookies, consent: true }"] id2_2_1["Target Name Match?"] id2_2_1_1["Yes -> Return 'consent' value (true)"] id2_3["{ name: Statistical%20cookies, consent: true }"] id2_3_1["Target Name Match?"] id2_3_1_1["Yes -> Return 'consent' value (true)"] id2_4["{ name: Marketing%20%26%20..., consent: true }"] id2_4_1["Target Name Match?"] id2_4_1_1["Yes -> Return 'consent' value (true)"] id2_5["{ name: Uncategorised%20Cookies, consent: true }"] id2_5_1["Target Name Match?"] id2_5_1_1["Yes -> Return 'consent' value (true)"] id3["gtm.uniqueEventId"] id4["Custom JavaScript Variable Logic"] id4_1["1. Find 'grvupdate' event in dataLayer history"] id4_2["2. Access 'consents' array from event"] id4_3["3. Loop/Find object where 'name' == targetName"] id4_4["4. Extract 'consent' property"] id4_5["5. Return value (true/false/undefined)"]

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 Advertising equals true.
  • 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 grvupdate event 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


References

javascript.info
Variables
doc.commandersact.com
consent.get | Commanders Act X

Last updated April 29, 2025

AI-assisted research. Sources, methodology and corrections · Source-checked guides and tools · Explore published answers

Ask Ithy AI