Skip to content

getDataLayerByEvent — GTM Variable Template for GTM

VARIABLES › GTM
getDataLayerByEvent CORE GTM

Retrieves the current dataLayer event object from window.dataLayer, or a first-level property value if specified. ↪️ Full Object: event object or {} if not found. ↪️ DataLayer Variable: property value or undefined if not found. ⚡ Result is cached


When to Use This

GTM Utilities

Access GTM-specific APIs: dataLayer, debug mode, container settings.


Examples

Example 6
CONFIGURATION
Return Type: Full Object | Event: "page_.*" | Use Regex: true
OUTPUT
{event: "page_view", page: {...}, ...}
Example 9
CONFIGURATION
Return Type: DataLayer Variable | Event: "page_view" | Key: "page"
OUTPUT
{page_language: "en", ...}

GTM Configuration

This is what you'll see when you open this variable in Google Tag Manager. Hover the icons for details.

Read-only Preview
getDataLayerByEvent
Event Name
💾 The event name to search for in window.dataLayer.

Supported formats:
  ✓ String (e.g. "page_view", "purchase, "ecommerce.*" )
🔎 Enable regex pattern matching (ecommerce.* matches "ecommerce_interaction", "ecommerce_purchase", etc.)
Return Type
Property Key
💾 Property to extract.

Supported formats:
  ✓ String (e.g. "page", "page_category, "ecommerce" )
Result Handling
Output Function (optional)
⚙️ Optional function to apply to the result before returning it.

Supported formats:
  ✓ Function

_____________
✏️  Examples

{{toCamelCase()}} - convert string to camelCase
{{undefinedTo("x")}} - convert undefined value to "x"
{{filter(GreaterThan(10))}} - keep values greater than 10


Under the Hood

📜 View Implementation Code
/**
 * Retrieves the most recent occurrence of a given event in window.dataLayer or a specific property.
 * Searches up to 1 level deep to handle wrapped structures.
 *
 * @param {string} data.evt - The event name to search for (Direct mode).
 * @param {boolean} [data.rgx] - Use regex matching for event name. Default: exact match.
 * @param {string} [data.add] - Mode: "fob" for full object, "dlv" for dataLayer variable.
 * @param {string} [data.key] - Property name to extract (when add="dlv").
 * @param {Function|string} [data.out] - Optional output handler.
 *
 * @returns {Object|*} Full object (or {}) when fob, property value (or undefined) when dlv.
 *
 * @framework ggLowCodeGTMKit
 */
const copyFromWindow = require('copyFromWindow');
const copyFromDataLayer = require('copyFromDataLayer');
const templateStorage = require('templateStorage');
const EVENT_ID_KEY = 'gtm.uniqueEventId';
const gtmId = copyFromDataLayer(EVENT_ID_KEY);
const getEventObjectByName = function(eventName, useRegex) {
    if (!gtmId || !eventName) return undefined;
    
    const CACHE_KEY = 'dlEvtByName';
    const cacheKey = CACHE_KEY + '_' + eventName + '_' + gtmId;
    const cache = templateStorage.getItem(cacheKey);
    if (cache && cache.obj !== undefined && cache.obj !== '') {
        return cache.obj;
    }
    
    const dataLayer = copyFromWindow('dataLayer');
    if (!dataLayer) return undefined;
    
    const cacheAndReturn = function(obj) {
        templateStorage.setItem(cacheKey, { obj: obj });
        return obj;
    };
    
    const eventMatches = function(evt) {
        if (!evt) return false;
        if (useRegex) {
            return evt.match(eventName);
        }
        return evt === eventName;
    };
    
    const findEventObject = function(item) {
        if (!item || typeof item !== 'object') return undefined;
        
        if (eventMatches(item.event)) {
            const itemId = item[EVENT_ID_KEY];
            if (itemId && itemId <= gtmId) {
                return item;
            }
        }
        
        for (let key in item) {
            if (!item.hasOwnProperty(key)) continue;
            const nested = item[key];
            if (nested && typeof nested === 'object' && eventMatches(nested.event)) {
                const nestedId = nested[EVENT_ID_KEY];
                if (nestedId && nestedId <= gtmId) {
                    return nested;
                }
            }
        }
        
        return undefined;
    };
    
    for (let i = dataLayer.length - 1; i >= 0; i--) {
        const item = dataLayer[i];
        if (!item) continue;
        
        const found = findEventObject(item);
        if (found) {
            return cacheAndReturn(found);
        }
    }
    
    return cacheAndReturn(undefined);
};
const safeFunction = fn => typeof fn === 'function' ? fn : x => x;
const out = safeFunction(data.out);
// ===============================================================================
// getDataLayerByEvent - Dire