Siirry dokumentaation sisältöön

Code snippets

Ready-to-use code patterns for consent-gated analytics, cookie settings links, consent state checks, and tag manager integration.

Viimeksi päivitetty:

Copy-paste patterns for the most common CookieBeam integrations. Each snippet is self-contained. For the full method list, see Browser API; for blocking mechanics, see Blocking.

Add type="text/plain" to prevent execution. The data-category attribute binds the script to a consent category, and data-src holds the real URL. CookieBeam activates the script when the visitor accepts that category.

<script type="text/plain" data-category="analytics"
  data-src="https://example.com/analytics.js"></script>

Inline scripts work the same way, without data-src:

<script type="text/plain" data-category="marketing">
  trackConversion('purchase');
</script>

Put a data-cb attribute on any element and it becomes a consent control. No JavaScript needed.

<a href="#" data-cb="show-preferencesModal">Cookie settings</a>

The JavaScript equivalent, for click handlers or SPA routers:

document.getElementById('cookie-link').addEventListener('click', function (e) {
  e.preventDefault();
  window.CookieBeam.showPreferences();
});

Listen to both events: cookiebeam:consentUpdate fires on an actual choice, cookiebeam:consentRestored fires on page load when a stored choice is re-applied.

<script>
  function onConsent(e) {
    if (e.detail.categories.indexOf('analytics') !== -1) {
      startAnalytics();
    }
  }
  window.addEventListener('cookiebeam:consentUpdate', onConsent);
  window.addEventListener('cookiebeam:consentRestored', onConsent);
</script>

If you only care about new choices (for example, to log them), listen to cookiebeam:consentUpdate alone. See Events reference for the full event detail.

Guard a block of code behind a category check. This only works after the runtime has initialized.

if (window.CookieBeam && CookieBeam.acceptedCategory('analytics')) {
  // safe to run analytics code
}

For code that might run before CookieBeam loads, combine this with the ready event.

Use loadScript to load an external script once and get a promise back. It won't load the same URL twice.

CookieBeam.loadScript('https://example.com/widget.js', { async: 'true' })
  .then(function () {
    initWidget();
  });

Useful inside consent event listeners when you need to load a vendor script dynamically rather than gating a static <script> tag.

The consent cookie is a URL-encoded JSON object. Read it from JavaScript and send it to your server, or parse it server-side from the Cookie header.

function readConsentCookie() {
  var match = document.cookie.match(/(?:^|;\s*)cb_cookie=([^;]*)/);
  if (!match) return null;
  try {
    return JSON.parse(decodeURIComponent(match[1]));
  } catch (e) {
    return null;
  }
}

var consent = readConsentCookie();
if (consent && consent.categories.indexOf('analytics') !== -1) {
  // visitor has accepted analytics
}

The cookie name defaults to cb_cookie but can be changed in configuration. See Consent cookie for the full field reference.

Wait for CookieBeam to be ready

The cookiebeam:ready event fires once after the runtime finishes initializing. API calls made before this point throw an error.

<script>
  window.addEventListener('cookiebeam:ready', function () {
    if (window.CookieBeam.acceptedCategory('analytics')) {
      startAnalytics();
    }
  });
</script>

Gate Google Analytics 4

Block the GA4 loader and its configuration until the visitor accepts analytics:

<script type="text/plain" data-category="analytics"
  data-src="https://www.googletagmanager.com/gtag/js?id=G-XXXXX"></script>
<script type="text/plain" data-category="analytics">
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', 'G-XXXXX');
</script>

Replace G-XXXXX with your measurement ID. CookieBeam activates both scripts in document order when the category is accepted, preserving the dependency chain.

If you load GA4 through Google Tag Manager instead, use Consent Mode v2 rather than script gating. GTM manages the tag lifecycle itself.

Gate Meta Pixel

Block the Meta Pixel until the visitor accepts marketing:

<script type="text/plain" data-category="marketing">
  !function(f,b,e,v,n,t,s)
  {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
  n.callMethod.apply(n,arguments):n.queue.push(arguments)};
  if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
  n.queue=[];t=b.createElement(e);t.async=!0;
  t.src=v;s=b.getElementsByTagName(e)[0];
  s.parentNode.insertBefore(t,s)}(window, document,'script',
  'https://connect.facebook.net/en_US/fbevents.js');
  fbq('init', 'YOUR_PIXEL_ID');
  fbq('track', 'PageView');
</script>

Replace YOUR_PIXEL_ID with your pixel ID. Since the pixel snippet is inline, no data-src is needed.

Accept-only-analytics button

Let the visitor accept a specific category without opening the full modal:

<button type="button" data-cb="accept-custom" data-categories="analytics">
  Allow analytics
</button>

Comma-separate multiple categories: data-categories="analytics,preferences". See Browser API for all data-cb actions.

Reject all

<button data-cb="accept-necessary">Only essential cookies</button>

Clear the consent state and delete the cookie. The banner re-shows on the next page load.

CookieBeam.reset(true);

Passing false (or no argument) clears the runtime state but leaves the cookie in the browser.

The consent event detail includes the resolved Consent Mode v2 signals. Each key is 'granted' or 'denied'.

<script>
  window.addEventListener('cookiebeam:consentUpdate', function (e) {
    var cm = e.detail.consentMode;
    if (cm && cm.analytics_storage === 'granted') {
      // Google analytics_storage is granted
    }
    if (cm && cm.ad_storage === 'denied') {
      // ad_storage is denied
    }
  });
</script>

The consentMode object is present only when Consent Mode integration is enabled.

Accept categories programmatically, from your own UI or an API call:

// Accept specific categories
CookieBeam.acceptCategory(['analytics', 'marketing']);

// Accept all categories
CookieBeam.acceptCategory('all');

// Accept only necessary (reject everything optional)
CookieBeam.acceptCategory('necessary');

This writes the consent record and activates gated scripts for the accepted categories, exactly as if the visitor had clicked the banner buttons.

Block iframes with a placeholder

CookieBeam's automatic blocking intercepts iframes inserted by JavaScript and shows a consent placeholder (shield) in their place. The placeholder names the vendor and category, with a button to accept and load the content.

Iframes hardcoded in your HTML start loading during parsing, before any script can intercept them. Create them dynamically in a gated script instead:

<script type="text/plain" data-category="marketing">
  var iframe = document.createElement('iframe');
  iframe.src = 'https://www.youtube.com/embed/VIDEO_ID';
  iframe.width = '560';
  iframe.height = '315';
  iframe.allow = 'autoplay; encrypted-media';
  document.getElementById('video-container').appendChild(iframe);
</script>

<div id="video-container"></div>

For iframes injected by a tag manager or widget loader, automatic blocking handles them without markup changes. See Blocking for details.

Fire an opt-out beacon

Some vendors expect an explicit "user opted out" signal. Use data-cookiebeam-run-on-disable to fire a script when its category is denied:

<script type="text/plain" data-category="analytics"
  data-src="https://analytics.example/optout-signal.js"
  data-cookiebeam-run-on-disable="true"></script>

This fires once per page load when the category is denied in a valid consent record. See Blocking for the full firing rules.

Attach metadata to the visitor's consent cookie:

CookieBeam.setCookieData({
  value: { campaign: 'spring-2026', variant: 'b' },
  mode: 'update'
});

Read it back with CookieBeam.getCookie('data').

Erase cookies by pattern

Remove all cookies starting with _ga:

CookieBeam.eraseCookies([/^_ga/]);

Remove specific cookies on a specific domain:

CookieBeam.eraseCookies(['_fbp', '_fbc'], '/', '.example.com');

Get the full preferences snapshot

var prefs = CookieBeam.getUserPreferences();
// {
//   acceptType: 'custom',
//   acceptedCategories: ['necessary', 'analytics'],
//   rejectedCategories: ['marketing'],
//   acceptedServices: { analytics: ['google-analytics'] },
//   rejectedServices: {}
// }

Switch the banner language

CookieBeam.setLanguage('de').then(function (success) {
  if (success) console.log('Switched to German');
});

See Languages for how detection and dynamic loading interact with this call.

In a GTM Custom HTML tag, check consent before firing:

<script>
  if (window.CookieBeam && CookieBeam.acceptedCategory('marketing')) {
    // safe to fire marketing tags
  }
</script>

Or use window.CookieBeamGTM, which is always available to GTM templates:

<script>
  var consent = window.CookieBeamGTM && CookieBeamGTM.getConsent();
  if (consent && consent.categories.indexOf('marketing') !== -1) {
    // fire tag
  }
</script>