- Help Center
- Track Goals
- Dynamic Goals
-
Getting Started
-
Configuration
- Targeting
- Split URL
- Product Testing
- Full Stack
- Experiment Management
- CSP Configuration
- Experiment Execution
- Reports
- Exit Popups
- GTM Integration
- Troubleshooting
- Performance Optimization
- Event-Triggered Changes
- Holdout Groups
- Split URL Pages
- URL Parameters
- DataLayer
- Menu Configurations
- Traffic Exclusion
- Experiment Scheduling
- Dynamic Element Changes
- Price Targeting
- Experience Scheduling
- Privacy
- Hash Changes
- Async Tracking
- Selective Installation
- CSS Selectors
- Vue.js Integration
- Page Content
- Multipage Split URL
- Organic Traffic
- Visual Editor
- Server-Side Testing
- Traffic Bucketing
- GDPR Warnings
- Statistical Confidence
- Browser Privacy
- Query Parameters
- Embedded Videos
- Tracking Code Execution
- Simultaneous Experiments
- Tags
- Deployments
- Disable Testing
- Locations
- Programmatic Bucketting
- Query Parameter Handling
- Convert Library
- Variation Previews
- Experiment Editing
- Opt-Out Script
- Data Reset
- Body Hiding
- Visit-Specific Variations
- Variation Styling
- Preview Issues
- Variation Editing
- Full-Site Testing
- Blinking Variations
- Cross-Domain Cookies
- Regex Support
- Conversion Tracking
- SPA Testing
- Project Setup
- Cross-Domain Tracking
- Geo-Targeting
- Analytics Tools
- Campaign Tags
- Previewing
- IDs
- Query String Targeting
- Bounce Rate Goals
- Bot Filtering
- Query String Variables
- Custom Audiences
- Redirects
- Baseline
- Tracking Code Location
- Secure Cookies
- AngularJS
- Cloudflare
- Code Installation
-
Track Goals
- Form Tracking
- Cookie Management
- iFrame Click Tracking
- Performance Optimization
- Revenue Tracking
- Interaction Goals
- Form Submissions
- Advanced Goals
- Lazy Loading
- Multi-Conversions
- URL Parameters
- Bounce Rate Goals
- DataLayer Integration
- Scroll Depth
- Social Interactions
- Page Views
- Marketo Forms
- Feature Analysis
- AJAX Forms
- Revenue Tracking via GTM
- Order Outliers
- Cumulative Revenue
- Goal Templates
- Adding Revenue Goals
- JS-Based Goals
- Goal Basics
- Google Analytics Goals
- Social Sharing
- Dynamic Goals
- Typeform Integration
-
Target Visitors
- Geolocation
- Interaction Goals
- Goal-Based Targeting
- Weather Targeting
- Cookie-Based Targeting
- Page Visits
- Audience Management
- Audience Segmentation
- Experiment Targeting
- Advanced Audience Creation
- Audience Templates
- Audience Creation
- Data Layer Integration
- Manual Activation
- JavaScript Conditions
- Device Targeting
- Language Targeting
- IP-Based Exclusion
- Visitor Management
- Page Tagging
- Cookies
-
Troubleshooting
- Google Warnings
- Visual Editor
- HTTPS Content
- Logs
- Support Options
- Bootstrap
- Cookie Blocking
- Change History
- Mobile Debugging
- AdWords
- Bot Exclusion
- Domain Issues
- Cloudflare Issues
- Monitoring
- Cloaking Penalties
- Goal Editor Issues
- Variations
- Snippet Performance
- Changes Not Saved
- Blocked Visual Editor
- Goal Testing
- Visual Editor Browsing
- Experiment Issues
- Installation Verification
- Data Leak Prevention
- Usage Limits
- Experiment Previews
- GA4 Revenue
- Chrome Debugger Logs
- SPA Errors
- Checkout JSON Error
-
Analyze Results
-
Integrations
- Google Analytics
- Cookie Consent Platforms
- Microsoft Clarity
- Plausible
- Marketo
- HubSpot
- Tealium
- Smartlook
- Klaviyo
- Salesforce CRM
- FullStory
- Snowplow Analytics
- Webflow
- GA4 Roles
- Amplitude
- Segment
- React
- BigCommerce
- WooCommerce
- Active Campaign
- Google Tag Manager
- Mixpanel
- Zapier
- Inspectlet
- Crazy Egg
- LanderApp
- Unbounce
- Instapage
- Drupal
- PrestaShop
- Magento
- Roistat
- Piano Analytics
- Heap Analytics
- Kissmetrics
- Mouseflow
- Adobe Analytics
- Clicky
-
Account Management
-
Developers
-
What's New
-
Common Questions
-
Shopify
How to Dynamically Trigger Conversions Based on dataLayer Events
- Introduction
- Prerequisites
- Scenario Setup
- Method 1: Polling for dataLayer and Monitoring Changes
- Method 2: URL Filtering
- dataLayer Condition Examples
- Conclusion
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.