Unlock Advanced Data Tracking: Using GTM’s Custom JavaScript Variables for Complex Data Extraction ??
Margub Alam
GA4 & Web Analytics Specialist | Google Tag Manager | Digital Analytics Consultant | Web Analyst | Mixpanel? - Product Analytic | Amplitude Analytics| CRO | Advanced Pixel Implementation
Google Tag Manager (GTM) is a powerful tool for managing marketing and analytics tags without modifying website code directly. While built-in variables in GTM provide essential data, some use cases demand a more advanced approach to extract complex data dynamically. This is where Custom JavaScript Variables (CJVs) become invaluable.
By leveraging CJVs, you can manipulate the Document Object Model (DOM), parse cookies, extract user interactions, and format data before sending it to analytics platforms.
Understanding Custom JavaScript Variables in GTM
A Custom JavaScript Variable is a GTM variable type that allows you to execute JavaScript code and return a value dynamically. These variables are particularly useful when:
To create a Custom JavaScript Variable in GTM:
A simple CJV follows this structure:
function() {
return "Hello, GTM!";
}
Now, let’s explore some advanced applications.
1. Extracting Data from Complex Page Elements
Many websites use dynamic content that doesn’t load immediately or exists deep within nested HTML elements. In such cases, you need JavaScript to traverse the DOM and extract relevant information.
Example: Capturing Product Price on a Dynamic E-commerce Site
If a product price is embedded within multiple <div> elements, such as:
<div class="product">
<span class="price">$199.99</span>
</div>
You can extract it using:
function() {
var priceElement = document.querySelector(".product .price");
return priceElement ? priceElement.textContent.trim() : null;
}
This method ensures you capture the price dynamically, even if the page structure changes slightly.
2. Extracting Query Parameters from URLs
Tracking specific URL parameters is common in marketing attribution. While GTM has a built-in "URL Query" variable, a CJV provides greater flexibility.
Example: Extracting and Formatting UTM Parameters
Let’s say you want to extract and format the utm_source parameter from URLs like:
https://example.com?utm_source=google&utm_medium=cpc
You can use:
function() {
var params = new URLSearchParams(window.location.search);
return params.has('utm_source') ? params.get('utm_source').toLowerCase() : "unknown";
}
This ensures:
3. Tracking User Scroll Depth Dynamically
Custom JavaScript can help track how far a user has scrolled on a page, beyond GTM’s built-in scroll variables.
Example: Returning the User’s Scroll Depth as a Percentage
function() {
var scrollTop = window.scrollY || document.documentElement.scrollTop;
var docHeight = document.documentElement.scrollHeight - window.innerHeight;
return docHeight > 0 ? Math.round((scrollTop / docHeight) * 100) : 0;
}
This variable can be sent to Google Analytics or other tracking tools to understand user engagement.
领英推荐
4. Extracting Data from JavaScript Variables or Objects
On sites using JavaScript frameworks (React, Angular, Vue), important data may be stored in JavaScript objects instead of HTML.
Example: Extracting User ID from a Global JavaScript Object
If a website stores user details in window.userData like:
window.userData = {
id: "12345",
name: "John Doe",
email: "[email protected]"
};
You can retrieve the id using:
function() {
return window.userData && window.userData.id ? window.userData.id : "guest";
}
This helps send user IDs to analytics tools for better tracking.
5. Extracting First-Party Cookie Values
Sometimes, user data is stored in cookies, which can be extracted using CJVs.
Example: Capturing a Cookie Value (e.g., User Session ID)
If a session cookie is stored as:
document.cookie = "session_id=abc123; path=/";
You can retrieve it using:
function() {
var match = document.cookie.match('(^|;)\\s*session_id\\s*=\\s*([^;]+)');
return match ? match[2] : null;
}
This is useful for tracking returning visitors without relying on third-party cookies.
Best Practices for Using Custom JavaScript Variables
To ensure optimal performance and accuracy:
Final Thoughts
Custom JavaScript Variables in Google Tag Manager provide unparalleled flexibility for extracting and transforming data. Whether you need to scrape dynamic page content, extract cookies, or track user interactions, CJVs can bridge the gap where built-in GTM features fall short.
By mastering these techniques, you can unlock deeper insights and optimize your analytics setup, ensuring more accurate data collection and enhanced marketing attribution.
Next Steps:
Would you like more specific implementations or troubleshooting tips? Let’s discuss in the comments! ??
I’m passionate about empowering organizations with data-driven decision-making while respecting user privacy.
Here’s how you can connect with me or view my work:
Upwork Profile: Upwork
Freelancer Profile: Freelancer
My Blog on GTM & Website Analytics: Google Tag Manager Solution
If you or someone in your network is looking for an experienced professional in this space, I’d love to connect and chat further!