How to Dynamically Trigger Conversions Based on dataLayer Events

Introduction

In the digital analytics realm, the dataLayer is a critical component for tracking user interactions on a website. It serves as a repository of information that can be used to understand user behavior and trigger specific actions, such as conversions, based on defined criteria. This article delves into techniques for dynamically triggering conversion tracking by monitoring dataLayer events, with a focus on practical implementation.

Prerequisites

  • Basic understanding of JavaScript
  • Familiarity with dataLayer concepts, often used in Google Tag Manager setups

Scenario Setup

Our goal is to trigger a conversion when a user completes an action that matches specific criteria, such as adding a product to their cart or reaching a confirmation page. These actions push relevant data to the dataLayer, which we can monitor to trigger conversions at precisely the right moment.

Method 1: Polling for dataLayer and Monitoring Changes

You will need to insert the following code in the Convert App > Your Project > Configurations > Global Project Javascript. Make sure you change the goal id that corresponds to the Custom JS goal that you have created on Convert.

Implementation


(function() {
    // Check for `dataLayer` existence and monitor changes
    const dataLayerPollInterval = setInterval(() => {
        if (typeof window.dataLayer !== 'undefined') {
            clearInterval(dataLayerPollInterval); // Stop polling
            startMonitoringDataLayer(); // Initialize monitoring
        }
    }, 100); // Poll every 100 milliseconds

    function startMonitoringDataLayer() {
        const originalPush = window.dataLayer.push;
        window.dataLayer.push = function(...args) {
            const result = originalPush.apply(this, args);
            checkDataLayerCondition(); // Check after each push
            return result;
        };
    }

    function checkDataLayerCondition() {
        // Example condition: Trigger when a specific event is pushed
        if (window.dataLayer.some(item => item.event === 'specificEventName')) {
            triggerConversion();
        }
    }

    function triggerConversion() {
        window.conv_q = window.conv_q || [];
        window.conv_q.push(["triggerConversion", "12345678"]);
        console.log('Conversion triggered.');
    }
})();

Method 2: URL Filtering

To ensure the script executes only on specified pages, add a URL filter:

if (!window.location.href.includes("example.com/section")) {
console.log("URL does not match criteria. Script will not execute.");
return;
}

dataLayer Condition Examples

Different scenarios necessitate various dataLayer checks. Here are some versatile examples:

1. Event Name Matching

Trigger conversions for specific events:

if (window.dataLayer.some(item = item.event === 'purchaseComplete')) {
triggerConversion();
}

2. Page Type or ID

For eCommerce sites, trigger based on page type or product ID:

if (window.dataLayer.some(item = item.pageType === 'productPage' && item.productId === '12345')) {
triggerConversion();
}

3. Multiple Conditions

Trigger when multiple conditions are met, such as an event and a minimum transaction total:

if (window.dataLayer.some(item = item.event === 'addToCart' && item.transactionTotal  100)) {
triggerConversion();
}

4. Presence of a Key

Trigger based on the existence of a key:

if (window.dataLayer.some(item = 'userLoggedIn' in item)) {
triggerConversion();
}

5. Sequence of Events

Monitor sequences, like viewing a product then adding it to the cart:

let viewedProduct = window.dataLayer.findIndex(item = item.event === 'productView');
let addedToCart = window.dataLayer.findIndex(item = item.event === 'addToCart');
if (viewedProduct !== -1 && addedToCart !== -1 && viewedProduct <addedtocart) {="{" triggerconversion();="triggerConversion();" }="}"></addedtocart)>

6. Time-based Conditions

Trigger actions based on interactions within a specific timeframe:

const recentInteractionTimeLimit = 60000; 
// 60 seconds
const now = Date.now();
if (window.dataLayer.some(item = item.event === 'interaction' && (now - item.timestamp) <= recentinteractiontimelimit))="recentInteractionTimeLimit))" {="{" triggerconversion();="triggerConversion();" }="}"></=>

Conclusion

By effectively monitoring the dataLayer for specific events or conditions, you can dynamically trigger conversions, enhancing the accuracy of your analytics and the effectiveness of your marketing strategies. This guide has provided the foundational knowledge and practical code snippets to implement these techniques, empowering you to create a responsive, data-driven user experience on your website.