Browser API
Control the consent banner from page JavaScript with the window.CookieBeam runtime API.
Last updated:
The CookieBeam loader installs a JavaScript API on the page as window.CookieBeam. The loader itself calls run() with your published configuration, so the methods below are ready to use as soon as the banner script has loaded. Callers that run too early receive an error telling them the runtime has not been initialized.
<script>
// Show the preferences modal when a "Cookie settings" link is clicked.
document.getElementById('cookie-settings').addEventListener('click', function () {
window.CookieBeam.showPreferences();
});
</script>
Initialization
run
CookieBeam.run(config?: RuntimeConfig): Promise<void>
Initialize the runtime with the given configuration. The published banner script calls this for you. You only need it for self-hosted installs or when re-initializing with a new configuration. Calling run() while a runtime is active destroys the previous one first.
destroy
CookieBeam.destroy(): void
Tear the runtime down: remove all DOM elements, disconnect event listeners, and clear internal state. After calling destroy(), the banner is gone and all methods throw until run() is called again.
Modal control
show
CookieBeam.show(createModal?: boolean): Promise<void>
Show the consent banner. If createModal is false, only shows the banner if the modal DOM already exists. The promise resolves when the modal is visible.
hide
CookieBeam.hide(): void
Hide the consent banner immediately.
showPreferences
CookieBeam.showPreferences(): Promise<void>
Open the preferences modal, where the visitor can toggle individual categories and services. The promise resolves when the modal is visible.
hidePreferences
CookieBeam.hidePreferences(): void
Close the preferences modal.
Read consent state
validConsent
CookieBeam.validConsent(): boolean
Returns true when the visitor has a valid, non-expired, non-pending consent record. A pending opt-in default (isPending: true) returns false.
acceptedCategory
CookieBeam.acceptedCategory(category: string): boolean
Check whether a specific category is accepted. Returns true if the visitor has consented to the named category (e.g. 'analytics').
if (CookieBeam.acceptedCategory('marketing')) {
loadMarketingPixel();
}
acceptedService
CookieBeam.acceptedService(service: string, category: string): boolean
Check whether a specific service within a category is accepted. Services give visitors per-vendor control inside a category.
if (CookieBeam.acceptedService('google-analytics', 'analytics')) {
startGA();
}
validCookie
CookieBeam.validCookie(cookieName: string): boolean
Check whether a named browser cookie exists and has a non-empty value. This is not a consent check. It doesn't consult categories, services, or consent state. Use acceptedCategory to decide whether a cookie's purpose is allowed.
getUserPreferences
CookieBeam.getUserPreferences(): UserPreferences
Returns the full preference snapshot:
{
acceptType: 'all' | 'custom' | 'necessary';
acceptedCategories: string[];
rejectedCategories: string[];
acceptedServices: Record<string, string[]>;
rejectedServices: Record<string, string[]>;
}
getCookie
CookieBeam.getCookie(field?: string, cookieName?: string): unknown
Read the parsed consent cookie, or one field of it. Without arguments, returns the full parsed cookie object. With a field name, returns just that field's value. The optional cookieName reads a different cookie than the default.
CookieBeam.getCookie(); // full consent cookie
CookieBeam.getCookie('categories'); // ['necessary', 'analytics']
CookieBeam.getCookie('revision'); // 3
See Consent cookie for the full schema.
getConfig
CookieBeam.getConfig(field?: string): unknown
Read the active runtime configuration, or one field of it.
CookieBeam.getConfig('mode'); // 'opt-in'
CookieBeam.getConfig('revision'); // 3
getTcfState
CookieBeam.getTcfState(): TcfState | null
Returns the current TCF state if TCF is enabled, or null otherwise. The returned object includes the TC string, vendor consents, purpose consents, and publisher restrictions.
getLastConsentModeEvidence
CookieBeam.getLastConsentModeEvidence(): LastConsentModeEvidence | null
Returns diagnostic data about the last Consent Mode gtag('consent', 'update', ...) call. Use it to verify that Consent Mode signals reached Google tags.
type LastConsentModeEvidence =
| { forConsentAt: string; status: 'sent'; protocolVersion: 2;
signals: Record<'analytics_storage' | 'ad_storage' | 'ad_user_data' | 'ad_personalization', 'granted' | 'denied'> }
| { forConsentAt: string; status: 'off' | 'failed' };
status: 'sent': thegtagcall fired successfully;signalsshows what was sent.status: 'off': Consent Mode is disabled in the configuration.status: 'failed': thegtagcall was attempted but failed (nogtagfunction found, or an error thrown).forConsentAt: theconsentTimestampof the record the update was for.
Returns null before the first consent write.
getAutomationAssessment
CookieBeam.getAutomationAssessment(): { score: number; confidence: number; automation: boolean } | null
Returns the runtime's assessment of whether the current visitor is human. The scorer watches for mouse movement timing gaps and input events to build a confidence score.
score: 0 to 1, where higher means more human-like. A detected automation scores 0.1; a visitor with regular interaction scores 0.5 and above.confidence: 0 to 1 confidence in the score.automation: the boolean verdict (true= likely automated).
Returns null when no runtime exists (before run() is called).
Note: hideFromBots is a separate feature that checks the user-agent string against a regex (/bot|crawler|spider|.../i). It does not read the automation scorer.
Change consent state
acceptCategory
CookieBeam.acceptCategory(
categories?: string | string[] | 'all' | 'necessary',
excludedCategories?: string[]
): void
Accept one or more categories. The first argument can be:
- A single category name:
'analytics' - An array of category names:
['analytics', 'preferences'] - The string
'all': accept every category - The string
'necessary': accept only necessary categories - Omitted or
undefined: accept all
The optional second argument excludes specific categories from the acceptance:
// Accept everything except marketing
CookieBeam.acceptCategory('all', ['marketing']);
This writes the consent cookie, activates scripts for accepted categories, and fires the cookiebeam:consentUpdate event.
acceptService
CookieBeam.acceptService(
service: string | string[] | 'all',
category: string
): void
Accept one service, multiple services, or all services within a category.
CookieBeam.acceptService('google-analytics', 'analytics');
CookieBeam.acceptService(['google-analytics', 'hotjar'], 'analytics');
CookieBeam.acceptService('all', 'analytics');
reset
CookieBeam.reset(deleteCookie?: boolean): void
Clear the in-memory consent state. If deleteCookie is true, also deletes the consent cookie, so the visitor is treated as if they never visited before. Without deleteCookie, the cookie remains but the runtime's internal state is cleared.
Passing true dispatches cookiebeam:consentWithdrawn on document.
Utilities
setLanguage
CookieBeam.setLanguage(
code: string,
forceUpdate?: boolean
): Promise<boolean>
Switch the banner's display language. Returns a promise that resolves to true if the switch succeeded, false if the language isn't available. The forceUpdate parameter forces a re-render even if the code matches the current language.
CookieBeam.setLanguage('de').then(ok => {
if (ok) console.log('Switched to German');
});
loadScript
CookieBeam.loadScript(
src: string,
attrs?: Record<string, string>
): Promise<boolean>
Inject an external script element and return a promise that resolves to true when it loads. The script loads only once per src. Repeated calls with the same URL return the first call's result. Use this to activate scripts after checking consent programmatically.
if (CookieBeam.acceptedCategory('analytics')) {
CookieBeam.loadScript('https://example.com/analytics.js', {
id: 'my-analytics',
'data-site': 'abc123'
});
}
setCookieData
CookieBeam.setCookieData(props: {
value: unknown;
mode?: 'update' | 'overwrite';
}): boolean
Store custom data in the consent cookie's data field. Returns true on success.
mode: 'update'(default): mergevalueinto the existingdataobject.mode: 'overwrite': replace thedatafield entirely.
CookieBeam.setCookieData({
value: { campaign: 'spring-2026' },
mode: 'update'
});
eraseCookies
CookieBeam.eraseCookies(
cookies: string | RegExp | (string | RegExp)[],
path?: string,
domain?: string
): void
Delete browser cookies by exact name or regex pattern. Optionally scope the deletion to a specific path and domain.
// Delete by exact name
CookieBeam.eraseCookies('_ga');
// Delete by pattern
CookieBeam.eraseCookies([/^_ga/, '_fbp'], '/', '.example.com');
GTM compatibility layer
The runtime also installs window.CookieBeamGTM for use in Google Tag Manager templates and custom HTML tags. These methods are also available on window.CookieBeam.
getConsent
CookieBeamGTM.getConsent(): {
categories: string[];
timestamp: string | null;
isValid: boolean;
}
Returns the current consent record as a simple object.
hasConsent
CookieBeamGTM.hasConsent(category: string): boolean
Whether a category is accepted. Equivalent to CookieBeam.acceptedCategory().
getConsentDetails
CookieBeamGTM.getConsentDetails(): {
necessary: boolean;
preferences: boolean;
analytics: boolean;
marketing: boolean;
}
Returns the four standard categories as booleans.
updateConsent
CookieBeamGTM.updateConsent(
categories: string | string[] | 'all' | 'necessary'
): void
Accept categories. Equivalent to CookieBeam.acceptCategory().
isBannerVisible
CookieBeamGTM.isBannerVisible(): boolean
Whether the consent banner or preferences modal is currently open.
showBanner / showPreferences
CookieBeamGTM.showBanner(): void
CookieBeamGTM.showPreferences(): void
Show the consent banner or preferences modal.
getConfig
CookieBeamGTM.getConfig(): {
mode: string;
autoShow: boolean;
revision: number;
gtmEnabled: boolean;
}
Returns a subset of the runtime configuration relevant to tag-manager templates.
version
CookieBeamGTM.version: string
The GTM bridge version string.
Events
The runtime dispatches DOM events you can listen to without polling. See Events reference for the full catalog with detail payloads, callback signatures, and event timing.
| Event | Target | When |
|---|---|---|
cookiebeam:ready | window | Runtime initialized |
cookiebeam:consentUpdate | window | Visitor made or changed a choice |
cookiebeam:consentRestored | window | Stored choice re-applied on page load |
cookiebeam_categories_changed | window | Accepted categories changed (legacy) |
cookiebeam:consentWithdrawn | document | reset(true) deleted a consent record |
The runtime also pushes cookiebeam_modal_shown and cookiebeam_modal_hidden to window.dataLayer for GTM triggers.
Data attributes
Put a data-cb attribute on any element to turn it into a consent control. The runtime handles clicks; no JavaScript needed. See Script attributes for the complete attribute reference.
| Value | Action |
|---|---|
show-preferencesModal | Open the preferences modal |
show-consentModal | Show the consent banner |
accept-all | Accept every category |
accept-necessary | Accept only necessary categories |
accept-custom | Accept categories in data-categories or data-category |
<a href="#" data-cb="show-preferencesModal">Cookie settings</a>
<button data-cb="accept-custom" data-categories="analytics,preferences">
Allow analytics
</button>
data-cc with the same values is accepted for backward compatibility. These controls work when manageScriptTags is enabled (the default).
Script gating attributes
Mark scripts with type="text/plain", data-category, and data-src to hold them back until consent. See Script attributes and Blocking for the full pattern.
Forms snippet
The separate forms snippet records consent from your own forms and exposes window.CookieBeamForms with collect(form) and record(payload).
Support diagnostics
window.CookieBeamConsent.debugInfo(): object
Returns a diagnostics snapshot of the runtime's current state. Always available, even when initialization fails. CookieBeam support may ask you to paste its output when troubleshooting an installation.