Chat
Ask me anything
Ithy Logo
Sign in to save

Custom HTML Tag for HubSpot & OneTrust Integration

Seamlessly manage HubSpot tracking based on user consent via OneTrust

computer screen with code and analytics dashboard

Highlights

  • Consent Management: Integrates OneTrust active groups to determine HubSpot script loading.
  • Do Not Track Handling: Sets or revokes the doNotTrack cookie based on browser and user consent.
  • Step-by-Step Logging: Detailed console logs for each step to aid debugging and transparency.

Overview

This custom HTML implementation for Google Tag Manager (GTM) is designed to control HubSpot tracking by evaluating OneTrust active groups status. It performs a series of checks to ensure that scripts are only loaded if the proper consent has been given. Furthermore, the script manages a doNotTrack cookie to respect user privacy preferences, setting the cookie when tracking is blocked and revoking it when tracking is allowed. All operational steps are logged to the console, which aids in debugging and ensures full transparency.

Script Structure and Explanation

1. Cookie Management Functions

The first set of functions in our script are dedicated to handling cookies. These include setting a cookie, getting a cookie, and erasing a cookie. Such functions are essential for handling the doNotTrack cookie based on whether the user opts out or consents to tracking via OneTrust.

Setting, Getting, and Removing Cookies

The following code snippets define the basic cookie operations which are used later to manage tracking preferences:


// Function to set a cookie with a specified name, value, and expiration in days
function setCookie(name, value, days) {
  var expires = "";
  if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    expires = "; expires=" + date.toUTCString();
  }
  document.cookie = name + "=" + (value || "") + expires + "; path=/";
  console.log("Cookie set:", name, "=", value);
}

// Function to retrieve a cookie value by name
function getCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i].trim();
    if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
  }
  return null;
}

// Function to remove a cookie by setting its expiration date in the past
function eraseCookie(name) {
  document.cookie = name + '=; Max-Age=-99999999;';
  console.log("Cookie removed:", name);
}
  

2. Consent Verification via OneTrust

This part of the script checks for OneTrust active groups to determine whether tracking should be allowed or rejected. The OneTrust tool populates a variable (or cookie) that contains the consent status for various categories. In this example, a specific group ID (e.g., "analytics" or "necessary") is used to decide whether to load the HubSpot script.

Checking OneTrust Active Groups

The script retrieves active groups from the OneTrust variable available in the global context or fallback cookie and identifies if the desired group is present for tracking.


// Retrieve the OneTrust active groups; adjust depending on your integration
var oneTrustActiveGroups = window.OnetrustActiveGroups || getCookie('OptanonConsent');
console.log("OneTrust Active Groups:", oneTrustActiveGroups);

// Replace 'your_onetrust_group_id' with the group associated with HubSpot tracking consent
var isTrackingAllowed = oneTrustActiveGroups && oneTrustActiveGroups.indexOf('your_onetrust_group_id') > -1;
console.log("Is tracking allowed based on OneTrust:", isTrackingAllowed);
  

3. Respecting Do Not Track (DNT)

The script also respects the Do Not Track (DNT) setting from the browser. If the DNT preference is enabled (typically represented as "1"), the script sets a specific doNotTrack cookie. Conversely, if DNT is disabled and a cookie exists, it revokes the cookie to allow tracking if consent is also provided by OneTrust.

Handling Do Not Track Preference

The following code snippet checks for DNT settings using browser properties. Depending on the value (or absence) of DNT, the script will set or remove the doNotTrack cookie.


// Check the Do Not Track status across different browser implementations
var doNotTrack = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
console.log("Do Not Track status:", doNotTrack);

if (doNotTrack === "1") {
  // User has enabled DNT; set doNotTrack cookie permanently
  setCookie("doNotTrack", "1", 365);
  console.log("Do Not Track cookie set because DNT is enabled.");
} else {
  // Remove any existing doNotTrack cookie if DNT is no longer enabled
  if (getCookie("doNotTrack")) {
    eraseCookie("doNotTrack");
    console.log("Do Not Track cookie revoked because DNT is disabled.");
  }
}
  

4. HubSpot Script Implementation

If the required consent parameters are met, the script dynamically loads the HubSpot tracking script. Rewriting the standard HubSpot script with logging ensures that you are aware when the tracking script is loaded and if any issues occur during its loading.

Dynamically Loading HubSpot Tracking Script

This function creates and appends a new script element to the document's head. Replace the script URL and HubSpot portal ID as needed.


// Function to load HubSpot tracking script dynamically
function loadHubSpot() {
  console.log("Initiating loading of HubSpot script...");
  (function(i, s, o, g, r, a, m) {
    i['HubSpotObject'] = r;
    i[r] = i[r] || function() {
      (i[r].q = i[r].q || []).push(arguments);
    };
    i[r].l = 1 * new Date();
    a = s.createElement(o);
    m = s.getElementsByTagName(o)[0];
    a.async = 1;
    a.src = g;
    m.parentNode.insertBefore(a, m);
  })(window, document, 'script', 'https://js.hs-analytics.net/analytics.js', 'hs');

  hs('init', 'YOUR_HUBSPOT_PORTAL_ID'); // Replace with your HubSpot Portal ID
  console.log("HubSpot tracking script loaded and initialized.");
}
  

5. Integrating All Components in a Unified Flow

The final part of our custom HTML brings the previous components together. It conducts the following checks in sequence:

  • Logs every step to the console for transparency.
  • Verifies OneTrust groups for the necessary consent.
  • Respects the Do Not Track preference.
  • Loads the HubSpot tracking script if conditions are met; otherwise, sets or maintains the doNotTrack cookie.

Unified Script Logic

The following behavior ensures compliance with user preferences and regulatory requirements while enabling or blocking HubSpot as needed:


// Begin the custom HTML tag logic for GTM

console.log("Custom GTM HTML Tag: Initialization started");

// -- Cookie Functions -- (setCookie, getCookie, eraseCookie defined previously)

// -- OneTrust Consent Check --
var oneTrustActiveGroups = window.OnetrustActiveGroups || getCookie('OptanonConsent');
console.log("OneTrust Active Groups:", oneTrustActiveGroups);
// Replace the following string with your specific consent group ID for HubSpot tracking
var isTrackingAllowed = oneTrustActiveGroups && oneTrustActiveGroups.indexOf('your_onetrust_group_id') > -1;
console.log("HubSpot tracking allowed:", isTrackingAllowed);

// -- Do Not Track Check --
var doNotTrack = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
console.log("Do Not Track status:", doNotTrack);

if (doNotTrack === "1") {
  setCookie("doNotTrack", "1", 365);
  console.log("DNT enabled: doNotTrack cookie set; HubSpot script will not load.");
} else {
  // User has not enabled DNT; revoke cookie if it exists
  if (getCookie("doNotTrack")) {
    eraseCookie("doNotTrack");
    console.log("DNT disabled: doNotTrack cookie removed.");
  }
  
  // -- Loading HubSpot Script If Consent Granted --
  if (isTrackingAllowed) {
    console.log("Consent granted based on OneTrust active groups. Proceeding to load HubSpot script.");
    loadHubSpot();
  } else {
    console.log("Consent not granted based on OneTrust settings. HubSpot tracking will not be loaded.");
    // Optionally, set a cookie or run additional logic here if further tracking restrictions are needed
  }
}

console.log("Custom GTM HTML Tag: Process completed");
  

Comprehensive Script Table

The following table outlines the key sections of the script along with their functionalities:

Section Functionality Key Code/Method
Cookie Management Set, get, and erase cookies to manage doNotTrack preference setCookie(), getCookie(), eraseCookie()
OneTrust Check Retrieve OneTrust active groups and verify tracking consent window.OnetrustActiveGroups, getCookie('OptanonConsent')
DNT Handling Check Do Not Track browser settings and manage the corresponding cookie navigator.doNotTrack, setCookie("doNotTrack", "1"), eraseCookie("doNotTrack")
HubSpot Loading Dynamically load HubSpot tracking script if consent granted loadHubSpot()
Logging Console logging at each critical step to facilitate debugging console.log()

Final Integrated HTML Code

Below is the complete HTML code that you can insert as a Custom HTML Tag through Google Tag Manager. Ensure you replace the placeholder values with your actual OneTrust group ID and HubSpot Portal ID.

<script>
  console.log("Custom GTM HTML Tag: Initialization started");

  // Function to set a cookie with name, value, and expiration in days
  function setCookie(name, value, days) {
    var expires = "";
    if (days) {
      var date = new Date();
      date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
      expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "") + expires + "; path=/";
    console.log("Cookie set:", name, "=", value);
  }

  // Function to get a cookie's value by name
  function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
      var c = ca[i].trim();
      if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
  }

  // Function to erase a cookie by name
  function eraseCookie(name) {
    document.cookie = name + '=; Max-Age=-99999999;';
    console.log("Cookie removed:", name);
  }

  // Function to load the HubSpot tracking script
  function loadHubSpot() {
    console.log("Initiating loading of HubSpot script...");
    (function(i, s, o, g, r, a, m) {
      i['HubSpotObject'] = r;
      i[r] = i[r] || function() {
        (i[r].q = i[r].q || []).push(arguments);
      };
      i[r].l = 1 * new Date();
      a = s.createElement(o);
      m = s.getElementsByTagName(o)[0];
      a.async = 1;
      a.src = g;
      m.parentNode.insertBefore(a, m);
    })(window, document, 'script', 'https://js.hs-analytics.net/analytics.js', 'hs');

    hs('init', 'YOUR_HUBSPOT_PORTAL_ID');  // Replace with your actual HubSpot Portal ID
    console.log("HubSpot tracking script loaded and initialized.");
  }

  // Retrieve OneTrust active groups from global variable or cookie
  var oneTrustActiveGroups = window.OnetrustActiveGroups || getCookie('OptanonConsent');
  console.log("OneTrust Active Groups:", oneTrustActiveGroups);

  // Replace 'your_onetrust_group_id' with your specific OneTrust group ID for HubSpot tracking consent
  var isTrackingAllowed = oneTrustActiveGroups && oneTrustActiveGroups.indexOf('your_onetrust_group_id') > -1;
  console.log("HubSpot tracking allowed:", isTrackingAllowed);

  // Check the Do Not Track status from the browser
  var doNotTrack = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
  console.log("Do Not Track status:", doNotTrack);

  if (doNotTrack === "1") {
    // If DNT is enabled, set a cookie and do not load HubSpot script
    setCookie("doNotTrack", "1", 365);
    console.log("DNT enabled: doNotTrack cookie set; HubSpot script will not load.");
  } else {
    // If DNT is disabled, remove doNotTrack cookie if it exists
    if (getCookie("doNotTrack")) {
      eraseCookie("doNotTrack");
      console.log("DNT disabled: doNotTrack cookie removed.");
    }

    // Load HubSpot script only if OneTrust consent is granted
    if (isTrackingAllowed) {
      console.log("Consent granted based on OneTrust active groups. Proceeding to load HubSpot script.");
      loadHubSpot();
    } else {
      console.log("Consent not granted based on OneTrust settings. HubSpot tracking will not be loaded.");
    }
  }

  console.log("Custom GTM HTML Tag: Process completed");
</script>
  

References

For additional detail and context regarding OneTrust integrations, HubSpot tracking, and GTM custom tags, consider reviewing the following resources:

Recommended Queries

Explore additional topics to further enhance your integration and tracking strategy:


Last updated March 21, 2025

AI-assisted research. Sources, methodology and corrections · Source-checked guides and tools · Explore published answers

Ask Ithy AI
Download Article
Delete Article