Implementing OneTrust and Google Consent Mode

Kai Omonijo

Deploying OneTrust to a website is often a simple task once you have covered the basics. I start with the same starter script I have built up over the years.

This implementation works either directly in the source code DOM, or via a client side tag manager such as Adobe Launch or Google Tag Manager.

There are customisations needed depending on the usecase. For example a multimarket website will need a different language attribute set. Or the account id may need to be dynamic based on loading the staging script versus the production script.

I have also implemented the below in the source code DOM and loaded tag manager in the OneTrust callback function; so the tag manager only loaded if consent was provided.


<script
  src="https://cdn.cookielaw.org/scripttemplates/otSDKStub.js"
  type="text/javascript"
  charset="UTF-8"
  data-dlayer-ignore="true"
  data-language="en"
  data-domain-script="7c4e9b2f-a1d8-6e3c-9f02-b8a41d5e6c90"
></script>

let consentLoaded = false;

window.dataLayer = window.dataLayer || [];

function gtag() {
  dataLayer.push(arguments);
}

gtag("consent", "default", {
  ad_personalization: "denied",
  ad_storage: "denied",
  ad_user_data: "denied",
  analytics_storage: "denied",
});

window.OptanonWrapper = function () {
  if (/(consent=true)/i.test(window.location.href) && !consentLoaded) {
    consentLoaded = true;
    return OneTrust.AllowAll();
  }

  if (/(consent=false)/i.test(window.location.href) && !consentLoaded) {
    consentLoaded = true;
    return OneTrust.RejectAll();
  }

  if (OneTrust.IsAlertBoxClosedAndValid()) {
    const googleConsent = {
      ad_storage: window.OnetrustActiveGroups?.includes("C0004")
        ? "granted"
        : "denied",
      ad_user_data: window.OnetrustActiveGroups?.includes("C0004")
        ? "granted"
        : "denied",
      ad_personalization: window.OnetrustActiveGroups?.includes("C0004")
        ? "granted"
        : "denied",
      analytics_storage: window.OnetrustActiveGroups?.includes("C0002")
        ? "granted"
        : "denied",
    };

    window.dataLayer.push({
      event: "consentUpdate",
      consent: googleConsent,
    });

    gtag("consent", "update", googleConsent);
  }
};