Transcend Docs

Cookiebot and airgap.js

Load airgap.js before Cookiebot, or restore addEventListener when Cookiebot must load first.

Load airgap.js before Cookiebot so both scripts can run. If you cannot change that order, restore the browser addEventListener method before airgap.js starts.

Symptom

Pages that load Cookiebot's uc.js before airgap.js can break airgap.js startup.

Cause

Cookiebot replaces EventTarget.prototype.addEventListener with its own method. That method does not match the browser method across JavaScript realms, such as an iframe. airgap.js reads addEventListener while it starts, and it needs the original browser method.

Preferred fix

Move the airgap.js script tag above the tag that loads Cookiebot's uc.js. airgap.js then reads the original method before Cookiebot replaces it.

Keep airgap.js first in <head>. See Installing airgap.js.

When you cannot reorder the scripts

Put this inline script after Cookiebot and immediately before the airgap.js script tag. It must run after Cookiebot has replaced addEventListener.

The script saves Cookiebot's method. It reads the original method from a hidden iframe, which is a new JavaScript realm. It assigns that method so airgap.js can cache it. After airgap.js is ready, it puts Cookiebot's method back.

A Content Security Policy (CSP) that blocks child frames will stop this script. Reorder the tags instead.

// CookieBot patches addEventListener in a way that breaks cross-realm composability.
// This script un-patches addEventListener during airgap.js init, so that airgap.js can
// cache references, and then restores the patched addEventListener implementation.

const { document, EventTarget } = self;

if (document && EventTarget) {
  // Store patched addEventListener and retrieve unpatched implementation from new JS realm
  const { addEventListener } = EventTarget.prototype;
  const iframe = document.createElementNS('http://www.w3.org/1999/xhtml', 'iframe');
  iframe.style.display = 'none';
  (document.documentElement || document).appendChild(iframe);
  const { EventTarget: CleanEventTarget } = iframe.contentWindow;
  iframe.remove();

  // Restore unpatched addEventListener
  EventTarget.prototype.addEventListener = CleanEventTarget.prototype.addEventListener;

  // Queue up addEventListener reset after airgap.js init
  (self.airgap = {
      readyQueue: [],
      ready(callback) {
          this.readyQueue.push(callback)
      },
      ...self.airgap
  }).ready(() => {
      // Reset back to original patched addEventListener
      EventTarget.prototype.addEventListener = addEventListener;
  });
}

On this page