---
title: "Code snippets"
description: "Ready-to-use code patterns for consent-gated analytics, cookie settings links, consent state checks, and tag manager integration."
url: "https://cookiebeam.com/docs/api-reference/snippets"
lang: "en"
last_updated: "2026-11-12"
---

# Code snippets

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

Copy-paste patterns for the most common CookieBeam integrations. Each snippet is self-contained. For the full method list, see [Browser API](https://cookiebeam.com/docs/api-reference/browser-api); for blocking mechanics, see [Blocking](https://cookiebeam.com/docs/configure/blocking).

## Gate a script on consent

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.

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

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

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

## "Cookie settings" link

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

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

The JavaScript equivalent, for click handlers or SPA routers:

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

## React to consent on every page view

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

```html
<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](https://cookiebeam.com/docs/api-reference/events-reference) for the full event detail.

## Check consent before running code

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

```js
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](#wait-for-cookiebeam-to-be-ready).

## Load a script after consent

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

```js
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.

## Read consent state for server-side use

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.

```js
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](https://cookiebeam.com/docs/api-reference/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.

```html
<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:

```html
<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](https://cookiebeam.com/docs/concepts/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:

```html
<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:

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

Comma-separate multiple categories: `data-categories="analytics,preferences"`. See [Browser API](https://cookiebeam.com/docs/api-reference/browser-api#data-attributes) for all `data-cb` actions.

## Reject all

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

## Reset consent (testing)

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

```js
CookieBeam.reset(true);
```

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

## Read the Consent Mode state

The consent event detail includes the resolved [Consent Mode v2](https://cookiebeam.com/docs/concepts/consent-mode-v2) signals. Each key is `'granted'` or `'denied'`.

```html
<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](https://cookiebeam.com/docs/concepts/consent-mode-v2) is enabled.

## Custom consent collection

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

```js
// 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:

```html
<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](https://cookiebeam.com/docs/configure/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**:

```html
<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](https://cookiebeam.com/docs/configure/blocking#run-on-disable-scripts) for the full firing rules.

## Store custom data on the consent record

Attach metadata to the visitor's consent cookie:

```js
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`:

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

Remove specific cookies on a specific domain:

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

## Get the full preferences snapshot

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

## Switch the banner language

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

See [Languages](https://cookiebeam.com/docs/configure/languages) for how detection and dynamic loading interact with this call.

## Google Tag Manager: check consent

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

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

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

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