Infinite Looping Issue in GTM Preview Mode
Resolving GTM preview mode infinite loops on HubSpot with OneTrust cookie consent
Key Insights
- Script Execution and Consent State: Ensure that the consent state is detected correctly before triggering any cookie consent revocation functions.
- GTM Preview Mode Nuances: GTM preview mode can alter script behavior, especially when combined with cookie consent management and tracking scripts.
- Integration and Testing: Review the integration order of GTM, HubSpot tracking, and OneTrust scripts and test using isolated environments to identify trigger conflicts.
Understanding the Issue
When using GTM preview mode on a HubSpot-hosted page, you may experience infinite page loops or constant reloads, a problem that often arises due to the way tracking and cookie consent scripts interact. Particularly in this case, the conflict stems from running OneTrust’s cookie consent mechanism alongside HubSpot’s tracking code. The specific script causing the issue — _hsq.push(['revokeCookieConsent']); — is intended to disable tracking when the user denies consent. In normal operation, outside of GTM preview mode, this procedure works as expected. However, in preview mode, GTM’s additional debugging layer may inadvertently cause repeated execution of these scripts. This results in persistent reloads or looping behaviour on your HubSpot-hosted page.
The core challenges revolve around:
- Script Execution Order: GTM preview mode can delay or alter when scripts execute, especially if multiple scripts are competing for the same event triggers.
- Consent State Management: If the consent revocation triggers a page reload which in turn reinitiates GTM preview mode tags, it creates a feedback loop.
- Environment Differences: Behavior in regular browsing versus preview mode can differ due to the debug code injected by GTM, which is not present during normal operation.
Detailed Analysis of GTM, HubSpot, and OneTrust Integration
GTM Preview Mode Characteristics
Google Tag Manager’s preview mode allows you to see which tags are firing and inspect various events as your page loads. However, the integration of preview mode on pages that host complex scripts like HubSpot tracking and OneTrust cookie consent can lead to unforeseen interactions:
- Debug Code Injection: GTM preview mode injects additional scripts and debugger code into your page. This may interfere with the normal flow of events, causing tags to fire repeatedly.
- Event Listener Duplication: In some cases, the debug environment can trigger duplicate event listeners that make it seem as if actions (such as clicking or page load events) are occurring multiple times.
- Variable Initialization: Variables used to track consent status might be reset or repeatedly updated due to the preview’s influence, thereby inadvertently activating the consent revocation function multiple times.
Integration of OneTrust and HubSpot
Integrating OneTrust for cookie consent with HubSpot’s tracking brings about its own set of challenges:
-
Cookie Consent Revocation: The command
_hsq.push(['revokeCookieConsent']);is used to disable HubSpot cookie tracking when a user opts out through OneTrust. This mechanism is typically executed within the OneTrust callback functionOptanonWrapper(), ensuring it fires when the user’s privacy preference is registered. - Script Execution Sequence: For proper functionality, it is crucial that HubSpot’s tracking scripts are aware of the user’s consent state before initializing. If the consent state is not set before the tracking code runs, you may have a condition where the revocation command is continuously re-triggered upon page reload.
- Consent Management Synchronization: A misalignment between when OneTrust updates the consent state and when GTM fires relevant tags can lead to repeated execution of the revocation command, particularly under GTM preview mode where events are captured in a more dynamic debugging environment.
Troubleshooting Strategies
Reviewing GTM Configuration
Tag and Trigger Settings
Start by examining your GTM container to ensure that tag triggers are appropriately configured. Infinite loops might be introduced by triggers that continuously fire on every page load or on repeated events:
- Verify that page view, click, or form submission triggers aren’t set to fire more than once unnecessarily. For instance, an “All Clicks” trigger might be too broad if not properly filtered.
-
If your GTM setup includes variables to monitor consent statuses (like
analytics_storageorad_storage), ensure they are being updated correctly before firing any tag that revokes consent. - Use GTM’s Preview and Debug mode to trace the exact sequence of events. Check if the revocation command is being executed repeatedly and modify your trigger conditions to prevent redundant acts.
Evaluating Data Layer Updates
Inspect your data layer for how consent states are pushed and updated. The expected behavior should be that the consent variable gets updated once at the page load, and subsequent actions rely on this single update. If it’s being updated repeatedly, it may inadvertently reinvoke the consent revocation process.
Use the GTM preview console to check for discrepancies in the variable values. If you find that the variable “revokeConsent” or similar gets set multiple times, consider implementing a lock mechanism in your JavaScript code that ensures the command runs only once per session.
Optimizing Consent Script Execution
Adjusting the Script Order
A critical aspect of troubleshooting involves checking the execution order of your scripts:
- Ideally, the OneTrust consent mechanism should execute and establish the consent state before HubSpot’s tracking script initializes.
- If the execution order is reversed due to GTM preview mode interference, then HubSpot’s trackers might initialize and then be “reversed” by the revocation command. To prevent this, consider modularizing the code using custom JavaScript in GTM so that it activates only after confirming that tracking should be prevented.
-
In some configurations, developers have found success by wrapping the call to
_hsq.push(['revokeCookieConsent']);within a function that first checks for the current consent state and a flag variable confirming that it has not been executed already.
Isolating the Issue
Temporarily remove or adjust the OneTrust consent script from your page running in GTM preview mode. By doing this, you can isolate whether the repeated reload cycle is triggered by the OneTrust integration or by GTM’s handling of the HubSpot script. As a test:
- Disable the OneTrust script and observe if the infinite reload issue ceases. If it does, then the OneTrust integration or its interplay with the HubSpot script is likely the source of the problem.
-
Alternatively, employ a simpler consent command in place of
_hsq.push(['revokeCookieConsent']);, such as_hsq.push(['doNotTrack']);if halting tracking is your goal, to see if this reduces looping behavior.
Utilizing Debugging and Monitoring Tools
GTM Debug Console
Leverage GTM’s built-in preview and debug console to:
- Monitor the sequence of tag firings and data layer updates. The console shows you exactly when your consent-related tags are activated.
- Identify any unusual repetitions of the consent revocation command.
- See if any other tags (such as those related to HubSpot tracking or page reload triggers) are inadvertently interacting with the OneTrust consent mechanism.
Browser Developer Tools
In addition to GTM’s console, use the browser’s developer tools:
- Inspect network activity to detect repeated HTTP requests that could indicate a looping sequence.
- Check for any JavaScript errors or warnings in the console that could provide additional clues.
- Use breakpoints in your JavaScript to pause execution at critical points, allowing you to monitor the state of the consent variables.
Implementing a More Controlled Consent Revocation Strategy
Custom JavaScript Approach
A proven solution is to create a custom JavaScript function which oversees the consent revocation process ensuring it only runs once per necessary refresh cycle. For example:
Code Implementation Example
// <!-- Begin custom consent revocation function -->
(function() {
// Flag to ensure revoke function runs only once per session/page load
var consentRevoked = false;
function revokeConsentIfNeeded() {
// Check a condition: for example, a global variable or dataLayer variable indicating denial of consent
if (!consentRevoked && typeof _hsq !== 'undefined') {
// Here, ensure your custom logic validates the user's consent decision before revoking
if (/* your condition to check that tracking is denied */) {
_hsq.push(['revokeCookieConsent']);
consentRevoked = true;
}
}
}
// Attach the function to the OneTrust callback or a suitable trigger event
if (typeof OptanonWrapper === 'function') {
OptanonWrapper();
revokeConsentIfNeeded();
}
})();
This code snippet demonstrates how you might encapsulate the revocation command inside a protective function that checks whether it has already been executed. Tweak the condition to match your specific requirements.
Ensuring Correct Timing
Making sure that the consent state is correctly updated before HubSpot’s script initialization is crucial. To achieve this:
- Adjust the sequence by delaying the HubSpot tracking script until after the OneTrust consent has been fully processed.
- Consider integrating a callback mechanism in your OneTrust setup that, once the consent state is finalized, triggers the rest of your page’s tracking.
- In cases where a delay might be suitable, use a timer or promise-based logic to ensure that scripts wait until the consent decision is fully emplaced.
Considerations When Using CDN and Other Tools
Content Delivery Networks (CDN) Impact
If your site employs a CDN such as Cloudflare, additional complications may arise:
- Rocket Loader Interference: Cloudflare’s Rocket Loader can change the timing of JavaScript execution, which may disrupt the sequence of events in GTM preview mode.
- Consider temporarily disabling Rocket Loader to determine if its behavior is contributing to the infinite loop.
Alternative Approaches
If the revocation approach continues to cause looping in preview mode, explore alternative strategies:
-
Do Not Track Implementation: In some scenarios, deploying
_hsq.push(['doNotTrack']);to anonymize data rather than revoking consent can be a functional fallback. - Consent Management Platforms (CMPs): Evaluate using other CMP features or fully integrated solutions that better handle the interplay between GTM preview mode and tracking scripts.
Testing and Finalizing Your Setup
Step-by-Step Testing Approach
To ensure your configuration resolves the infinite loop without sacrificing functionality, follow these testing steps:
- Run in Regular Mode: Test your site outside of GTM preview mode to confirm that the consent revocation works as expected.
- Enable GTM Preview Mode: Activate GTM preview mode and closely monitor the debug console to identify if and when the loop initiates.
- Isolate Components: Temporarily disable either the OneTrust script or any extra GTM triggers to narrow down the cause.
- Review Network Logs: Use your browser’s developer tools to observe network traffic and confirm that excessive reloads or duplicated requests are halted.
- Convergence Testing: Once isolated, reintroduce the components gradually until the complete integrated deployment replicates normal behavior safely.
HTML Table of Troubleshooting Steps
| Step | Description | Action |
|---|---|---|
| 1 | Review GTM Triggers | Inspect and adjust tag triggers to avoid repeated firing. |
| 2 | Inspect Data Layer | Verify only a single update for consent state is pushed. |
| 3 | Modify Script Order | Delay HubSpot tracking until after consent state is finalized. |
| 4 | Test with/without OneTrust | Isolate the OneTrust script to confirm its effect on looping. |
| 5 | Monitor Network Activity | Use developer tools to identify repeated requests. |
Conclusion and Final Thoughts
Infinite page loops in GTM preview mode when using a HubSpot-hosted page combined with OneTrust for cookie consent is primarily caused by conflicts in script execution and the nuanced behavior of GTM’s debugging mode. Key elements include ensuring the proper sequencing of consent state updates and tracking scripts, restricting redundant event triggers, and making use of custom JavaScript to control the revocation command precisely.
By isolating components, simplifying your execution logic, and leveraging both GTM’s and your browser’s debugging tools, you can diagnose and resolve the infinite loop issue. For many, the solution involves delaying the execution of tracking scripts until the consent state has been cemented, or employing alternative commands like _hsq.push(['doNotTrack']); to manage user privacy without triggering repeated reloads.
Additionally, always be mindful of other factors such as CDN behavior (e.g., disabling Rocket Loader on Cloudflare) which might interfere with script execution order. With careful testing and a more controlled implementation, you can simultaneously use HubSpot’s tracking, OneTrust’s cookie consent, and GTM’s preview mode without encountering disruptive loops.
References
- Google Consent Mode v2 implementation - HubSpot Community
- HubSpot forms sending 2 events to GA on each submission - HubSpot Community
- How to prevent HubSpot tracking prior consent - Usercentrics
- OneTrust Article on Cookie Consent - OneTrust
- Google Tag Manager Debug Mode - Analytics Mania
- Google Analytics Tag in GTM Still Running - Analytics Mania
- GTM Preview Mode not Working - Analytics Mania
Recommended Queries for Further Exploration
Last updated February 21, 2025