Mastering Cookie Management: Deleting Old OneTrust Cookies from Subdomains with GTM
A comprehensive guide to crafting a Google Tag Manager script for precise cookie removal, ensuring cleaner user experiences and compliance.
Essential Insights: Key Takeaways
- Precision Deletion: Targeting specific OneTrust cookies on subdomains requires careful JavaScript logic within a Google Tag Manager (GTM) Custom HTML tag, focusing on correct domain and path attributes.
- GTM as an Executor: GTM doesn't inherently delete cookies but can deploy custom scripts that perform this action, typically triggered on page load or specific consent-related events.
- Critical Considerations: Factors like HttpOnly flags (which prevent client-side deletion), proper OneTrust configuration, and thorough testing are paramount for successful and compliant cookie management.
The Challenge: Eradicating Lingering Subdomain Cookies
Managing cookies, especially those related to consent management platforms like OneTrust, can become complex when dealing with subdomains. Old or legacy OneTrust cookies, previously set on a subdomain, might persist even after configuration changes or user preference updates. These lingering cookies can potentially lead to inconsistencies in user experience or even compliance issues. Google Tag Manager (GTM) offers a powerful way to address this by allowing you to deploy custom scripts. This guide will walk you through creating a script in GTM to effectively find and delete these old OneTrust cookies from your subdomains.
Why GTM for Cookie Deletion?
Google Tag Manager is a versatile tool primarily used for deploying tracking and marketing tags. However, its ability to inject custom JavaScript (via Custom HTML tags) onto your web pages makes it suitable for tasks like cookie manipulation. By using GTM, you can centralize the cookie deletion logic, manage its deployment across various pages or conditions, and update it without directly modifying your website's codebase.
Understanding Cookies, Domains, and Subdomains
Before diving into the script, it's crucial to understand the fundamentals of how cookies interact with domains and subdomains, as this knowledge is key to successful deletion.
How Cookies Work
Cookies are small pieces of data stored by a web browser. When a user visits a website, the server can send a cookie to the browser, which then stores it. On subsequent requests to the same server (or a server within the cookie's specified domain), the browser sends the cookie back. This allows websites to remember information about the user, such as login status, preferences, or consent choices.
Domain and Path Specificity: The Keys to Deletion
A cookie's accessibility is governed by its Domain and Path attributes:
- Domain Attribute: Specifies which hosts can receive the cookie. If not set, it defaults to the host that set the cookie (but not its subdomains). If set to
.example.com(note the leading dot), it's accessible byexample.comand all its subdomains (e.g.,sub.example.com). A cookie set onsub.example.comwithout a specific domain attribute is typically only accessible bysub.example.com. - Path Attribute: Defines the URL path that the cookie is valid for. If set to
/, it's valid for all paths on the specified domain.
To delete a cookie using JavaScript, you must set its expires attribute to a past date. Crucially, the domain and path used in the deletion command must match those with which the cookie was originally set. This is often the trickiest part, especially with older cookies whose exact setting parameters might be unknown.
Challenges with Subdomains
The Same-Origin Policy, a fundamental browser security mechanism, restricts how scripts from one origin (domain/subdomain) can interact with resources from another. While a script on main.example.com generally cannot directly delete a cookie specifically set for sub.example.com only, if the GTM script is running on the subdomain itself, it has the authority. Furthermore, if cookies were set by the main domain (e.g., example.com) with a scope that includes subdomains (e.g., Domain=.example.com), a script running on the subdomain can delete them by specifying the correct parent domain and path.
This is why our GTM script, intended to run on pages within the subdomain, will attempt deletion using various relevant domain specifications.
Visual representation of cookie consent management elements.
Step-by-Step: Crafting Your GTM Cookie Deletion Tag
Let's proceed with creating the Custom HTML tag in GTM to house our JavaScript logic for deleting old OneTrust cookies.
Step 1: Identify Target OneTrust Cookies
First, you need to know the names of the OneTrust cookies you intend to delete. Common OneTrust cookies related to consent often include:
OptanonConsent: Stores the user's consent preferences for different cookie categories.OptanonAlertBoxClosed: Indicates if the user has closed/dismissed the cookie consent banner.OptanonActiveGroups: Sometimes used to list active consent groups.
You might have older or custom-named OneTrust cookies. Use your browser's developer tools (usually under "Application" > "Cookies") to inspect cookies on your subdomain and identify the exact names. The table below lists some common OneTrust cookies and their typical roles.
Common OneTrust Cookies and Their Roles
This table outlines some frequently encountered OneTrust cookies. Note that the exact cookies and their attributes can vary based on your specific OneTrust configuration and version.
| Cookie Name | Typical Purpose | Commonly Client-Accessible (Not HttpOnly)? | Deletion Notes |
|---|---|---|---|
| OptanonConsent | Stores user consent preferences for cookie categories. | Yes | Primary target for deletion if consent needs resetting. |
| OptanonAlertBoxClosed | Indicates if the cookie banner/alert has been dismissed by the user. | Yes | Deleting this can make the banner reappear. |
| OptanonActiveGroups | May store identifiers for consent categories the user has agreed to. | Yes | Part of the consent state. |
| eupubconsent-v2 | Related to IAB TCF v2 framework consent string. | Yes | Relevant if using IAB framework. |
Always verify the exact cookie names and their properties (like domain and path) on your specific subdomain using browser developer tools before attempting deletion.
Step 2: Develop the JavaScript Deletion Logic
The core of our solution is a JavaScript snippet that iterates through the identified cookie names and attempts to delete them by setting their expiration date to the past. It will also try various domain and path combinations to maximize the chances of successful deletion.
<script type="text/javascript">
(function() {
var cookiesToDelete = ['OptanonConsent', 'OptanonAlertBoxClosed', 'OptanonActiveGroups']; // Add other old OneTrust cookie names if necessary
var currentHostname = window.location.hostname; // e.g., 'sub.example.com'
var domainParts = currentHostname.split('.');
var pathsToTry = ['/']; // Usually cookies are set at root path, add others if needed e.g. ['/', '/specificpath']
// Function to delete a cookie
function deleteCookie(name, domain, path) {
var cookieString = name + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
if (path) {
cookieString += "; path=" + path;
}
if (domain) {
cookieString += "; domain=" + domain;
}
document.cookie = cookieString;
// console.log('Attempted to delete: ' + name + ' with domain: ' + domain + ' and path: ' + path); // For debugging
}
cookiesToDelete.forEach(function(cookieName) {
pathsToTry.forEach(function(path) {
// Attempt 1: Delete with the specific subdomain
deleteCookie(cookieName, currentHostname, path);
// Attempt 2: Delete with the parent domain (e.g., .example.com)
// This is crucial for cookies set by the parent domain to be shared with subdomains.
if (domainParts.length >= 2) {
var parentDomain = '.' + domainParts.slice(-2).join('.'); // e.g., '.example.com'
deleteCookie(cookieName, parentDomain, path);
}
// Attempt 3: Delete with the base domain (e.g., example.com, without leading dot)
// Less common for subdomain-specific cookies, but worth trying for thoroughness.
if (domainParts.length >= 2) {
var baseDomain = domainParts.slice(-2).join('.'); // e.g., 'example.com'
deleteCookie(cookieName, baseDomain, path);
}
// Attempt 4: Delete without specifying domain (defaults to current hostname, more restrictive scope)
deleteCookie(cookieName, null, path);
});
});
// Optional: Clear related OneTrust local storage items if any were used
// if (window.localStorage) {
// Object.keys(localStorage).forEach(function(key) {
// if (key.toLowerCase().includes('onetrust') || key.toLowerCase().includes('optanon')) {
// localStorage.removeItem(key);
// // console.log('Removed localStorage item: ' + key); // For debugging
// }
// });
// }
console.log('OneTrust cookie deletion script executed for subdomain: ' + currentHostname);
})();
</script>
Understanding the Script:
- It defines an array
cookiesToDeletewith the names of OneTrust cookies. Customize this list. - The
deleteCookiefunction constructs the cookie string with an expiry date in the past. - It iterates through each cookie name and attempts deletion using:
- The full current hostname (e.g.,
subdomain.example.com). - The parent domain prefixed with a dot (e.g.,
.example.com), which covers cookies set to be accessible by the main domain and all its subdomains. - The base domain (e.g.,
example.com). - No explicit domain (letting the browser default to the current hostname).
- The full current hostname (e.g.,
- It primarily attempts deletion for the root path (
/). If you suspect cookies were set with more specific paths, you can add them to thepathsToTryarray. - An optional section for clearing
localStorageitems related to OneTrust is commented out. Use with caution and verify item names.
Step 3: Creating the Custom HTML Tag in GTM
- Log in to your Google Tag Manager account and navigate to your container.
- Go to "Tags" in the left-hand menu and click "New."
- Name your tag descriptively, e.g., "OneTrust - Delete Old Subdomain Cookies."
- Click on "Tag Configuration" and choose "Custom HTML" as the tag type.
- Paste the entire JavaScript code (including the
<script>tags) into the HTML field.
Step 4: Configuring the Trigger
The trigger determines when your cookie deletion script will execute.
- Below the Tag Configuration, click on "Triggering."
- Choose an appropriate trigger. Common choices include:
- Page View (All Pages or specific subdomain pages): This will run the script every time a page loads on the configured scope. If these are truly "old" cookies you want to get rid of once, this might be too frequent after the initial cleanup. Consider limiting its run or removing it after verification.
- DOM Ready: Ensures the basic HTML structure is loaded.
- Window Loaded: Waits for all resources, including images, to load.
- Custom Event: If you want to run this script only under specific circumstances (e.g., after a user updates consent settings and a corresponding event is pushed to the data layer like
OneTrustGroupsUpdated), a custom event trigger is more targeted. For general cleanup of old cookies, Page View might be initially suitable.
- If using a Page View trigger, you might want to configure it to fire only on "Some Page Views" and set a condition like "Hostname contains yoursubdomain.yourdomain.com" to ensure it only runs on the intended subdomain.
- Save the trigger and then save the tag.
Step 5: Testing and Publishing
- Preview: Before publishing, use GTM's "Preview" mode. Open your subdomain in a new browser tab (with the GTM preview pane active).
- Verify Execution: Check the GTM debug console to see if your tag fired on the appropriate trigger.
- Inspect Cookies: Use your browser's developer tools (Application > Cookies) to see if the targeted OneTrust cookies have been removed after the tag fires. You might need to refresh the page or navigate to see the effect. Check the console logs from the script for debugging messages if you uncommented them.
- Iterate if Necessary: If cookies are not deleted, double-check their names, paths, and domains. The script attempts common variations, but edge cases might exist.
- Publish: Once you've confirmed the script works as expected, publish your GTM container.
After a period, once you are confident that old cookies have been cleared from your active user base, you might consider disabling or removing this tag to avoid unnecessary script execution on every page load, unless continuous "cleanup" is desired for some reason (which is unusual).
Visualizing Cookie Deletion Strategy Factors
Successfully deleting cookies, especially in a complex environment involving subdomains and consent management, depends on several factors. The radar chart below illustrates key aspects and their relative importance or complexity in a typical cookie deletion strategy via GTM. Higher values suggest greater importance or complexity to manage for that factor.
This chart highlights that Cookie Attribute Specificity (correctly identifying and using the original domain/path) and Script Robustness (handling various scenarios) are highly critical. Equally important are Testing Thoroughness to ensure the script works as intended without side effects, and Compliance Alignment to ensure the actions are in line with privacy policies. GTM Trigger Precision dictates when the script runs, impacting its effectiveness and efficiency, while HttpOnly Awareness acknowledges a key limitation.
Important Considerations for Cookie Management
While the GTM script provides a practical solution, several factors must be kept in mind:
HttpOnly Cookies
If a cookie is set with the HttpOnly flag, it cannot be accessed or modified by client-side JavaScript. This is a security measure to prevent cross-site scripting (XSS) attacks from stealing cookies. The script provided will not be able to delete HttpOnly cookies. Such cookies must be managed server-side or allowed to expire naturally. Fortunately, most OneTrust consent-related cookies are typically not HttpOnly as they need to be read by client-side scripts.
Script Scope and Limitations
The script's effectiveness is tied to the accuracy of cookie names, domains, and paths. It operates within the constraints of browser security models. Ensure your OneTrust configuration itself is correctly set up to manage current and future cookie consent, as this script is primarily for cleaning up *old* or misconfigured cookies.
Compliance and Privacy (GDPR, CCPA)
Any action involving cookies, including deletion, must align with your organization's privacy policy and relevant data protection regulations like GDPR or CCPA. Ensure that deleting these cookies is consistent with user expectations and your consent management strategy. For instance, if a user withdraws consent, deleting associated cookies is often a required step.
OneTrust Configuration
Ideally, your OneTrust platform should be configured to handle cookie lifecycles correctly based on user consent. This script should be seen as a supplementary tool for specific cleanup tasks rather than a replacement for proper OneTrust setup and ongoing consent management. OneTrust itself often provides mechanisms or guidance for handling cookies based on consent status, including autoblocking and integration with Google Consent Mode.
This video discusses using OneTrust and Google Tag Manager, particularly focusing on blocking cookies with the OptanonConsent variable, which is relevant to understanding how these tools interact in managing cookie consent.
Mapping the Cookie Deletion Journey
The mindmap below outlines the key stages and considerations involved in the process of deleting old OneTrust cookies from a subdomain using Google Tag Manager. It provides a visual overview of the entire workflow, from initial understanding to post-deployment monitoring.
(.yourdomain.com, subdomain.yourdomain.com, null)"] id3_2_4["Logic for Path Specification (primarily '/')"] id3_2_5["Optional: localStorage cleanup"] id3_3["Configure GTM Trigger (e.g., Page Load on Subdomain, DOM Ready, Custom Event)"] id4["Testing & Deployment"] id4_1["Utilize GTM Preview & Debug Mode"] id4_2["Inspect Cookies via Browser Developer Tools"] id4_3["Test Across Different Browsers/Scenarios"] id4_4["Publish GTM Container Changes"] id5["Key Considerations & Best Practices"] id5_1["HttpOnly Flag Limitation (JS cannot delete)"] id5_2["Script Idempotency (Safe to run multiple times)"] id5_3["User Experience (e.g., banner reappearance)"] id5_4["Privacy Compliance (GDPR, CCPA alignment)"] id5_5["Long-term: Proper OneTrust Configuration"] id5_6["Ongoing Monitoring & Script Maintenance"]
This mindmap visually breaks down the process into manageable phases: understanding the foundational concepts, preparing for implementation, the GTM setup itself, thorough testing, and finally, crucial ongoing considerations to ensure effectiveness and compliance.
Frequently Asked Questions (FAQ)
How do I find the exact domain and path a cookie was set with?
You can use your browser's developer tools. In most browsers (like Chrome, Firefox, Edge):
- Open Developer Tools (usually by pressing F12).
- Navigate to the "Application" tab (Chrome/Edge) or "Storage" tab (Firefox).
- Under "Cookies," select the domain/subdomain you are inspecting.
- A table of cookies will appear. Click on a specific cookie to see its details, including its "Domain" and "Path" attributes.
This information is crucial for ensuring your GTM deletion script targets the cookies correctly.
What if the OneTrust cookies are HttpOnly?
If a cookie is marked with the `HttpOnly` flag, it cannot be accessed or deleted by client-side JavaScript, including scripts run via Google Tag Manager. This is a security feature. HttpOnly cookies can only be modified or deleted by the web server that set them, or they will expire naturally based on their `Max-Age` or `Expires` attribute.
Most OneTrust cookies that manage client-side consent state (like `OptanonConsent`) are typically *not* HttpOnly because JavaScript needs to read them. However, always verify this using your browser's developer tools.
Can this GTM script delete cookies set on the main domain from a subdomain?
Yes, under certain conditions. If a cookie was set by the main domain (e.g., `example.com`) with its `Domain` attribute specified as `.example.com` (allowing access by all subdomains), then a script running on `subdomain.example.com` can delete this cookie by specifying `domain: '.example.com'` in the deletion command.
However, a script on `subdomain.example.com` cannot delete a cookie that was set by `main.example.com` *only* for `main.example.com` (i.e., without the leading dot or a domain attribute that includes the subdomain). The browser's Same-Origin Policy generally prevents this direct cross-origin modification unless the cookie was explicitly shared.
What is the best GTM trigger for this cookie deletion script?
The "best" trigger depends on your goal:
- For a one-time cleanup of very old cookies: A "Page View - DOM Ready" or "Page View - Window Loaded" trigger, perhaps limited to run only once per user or for a limited time period (which requires more advanced GTM setup, like using cookies to track if the script has run), might be suitable. After cleanup, the tag could be paused or removed.
- For ongoing management based on consent changes: A "Custom Event" trigger is ideal. For example, if OneTrust pushes an event like `OneTrustGroupsUpdated` to the data layer when consent changes, you can trigger your script on this event to clean up cookies related to newly opted-out categories.
- General periodic cleanup (less common): A "Page View" trigger on specific subdomain pages. Be mindful of performance if the script runs very frequently.
Always scope your trigger carefully (e.g., to fire only on the relevant subdomain) to avoid unintended execution.
Recommended Further Exploration
- How to debug JavaScript cookie operations in Google Tag Manager?
- What are the best practices for OneTrust integration with subdomains and Google Tag Manager?
- Explore advanced GTM triggering conditions for conditional script execution.
- Understand the impact of Same-Origin Policy on cross-domain cookie management.
References
Last updated May 15, 2025