Consent
JavaScript SDK v1.4.0 — Consent
Consent, CMP passthrough, and Global Privacy Control
The SDK is the browser-side consent store (_optima_consent, see Storage). Three sources can set it:
- The site, via
consent.set({purpose: boolean}, meta?). - An existing CMP the tenant already runs, passed through automatically at startup:
- IAB TCF v2: read via
window.__tcfapi; the rawtcStringis captured ontcloaded/useractioncompleteand carried on every request. - Google Consent Mode: the SDK reads any
dataLayer['consent', 'default'|'update', {...}]commands already queued and wraps futuredataLayer.pushcalls to keep catching them, forwarding the seven Consent Mode keys (ad_storage,analytics_storage,ad_user_data,ad_personalization,functionality_storage,personalization_storage,security_storage).
- IAB TCF v2: read via
- Global Privacy Control: when
navigator.globalPrivacyControl === true, every purpose named inconsent.gpcDeniesthat has no decision yet is recordedfalseand sent once to/edge/v1/consent, so the CDP holds the opt-out. A GPC deny does not count as the visitor's decision: the banner still asks, and hits are still buffered (in"buffer"mode) until the visitor decides. It never overrides an explicit choice. - Validation:
consent.setaccepts strict booleans only ("false"is notfalse) and purpose names of 1–128 characters, at most 32 per call; invalid entries are dropped with anerrorevent ({op: "consent", reason: "invalid_input", dropped}), and a call with nothing valid (including{}) is rejected — nothing stored, nothing sent.setKeys/setTCF/setGCMreject input beyond the contract caps the same way and keep the previous value.consent.get()returns a frozen copy. - Multiple tabs: a decision taken in one tab reaches the others through the
storageevent (consent:changefires there too); areset()in one tab moves the others to the new device id.
new OptimaSDK(resolveConfig({
key: "oek_shop_…",
consent: { gpcDenies: ["marketing", "ads"] },
}));consent.source: "cmp" hands the consent conversation to the CMP entirely. Concretely, the SDK then: (a) never declares its own purposes on any request — only the CMP carriers (tcf/gcm/keys) ride, so the gateway reads the request as undeclared and the operator's cmp_mode decides what that means; (b) never renders a served banner_consent item — it is surfaced as a content:item event instead (one debug log line the first time), so your CMP can drive itself off it without two banners asking the same visitor the same question; and (c) never buffers before a decision (beforeDecision is forced to "send"), because the decision the SDK would be waiting for is not its own to make. consent.set still writes the local store — the SDK needs it for tracker gating — it just does not present it as a declaration.
Declaring purposes (consent.source: "optima", the default): before the visitor has decided anything, requests carry no purposes key at all — the server reads that as "undeclared" and applies the tenant's consent_mode. Once a decision exists the key is always present, including as an empty purposes: [] after a reject-all: that is an explicit refusal, and the gateway/worker treat it as such rather than as silence. (Backend: in consent_mode=optional the hits are still collected — optional means consent governs use, not collection — but stamped with no purpose provenance instead of the tenant's full collection set; in require mode a refusal of a required purpose is the usual missing_consent drop.)
Load order (Google Consent Mode): the SDK's dataLayer.push wrapper only sees pushes made after it installs. If GTM (or another CMP) loads and reassigns dataLayer.push itself after this SDK has already wrapped it, that later assignment wins and the SDK stops seeing consent updates — there is no re-wrap polling. Load the CMP/GTM before this SDK's script tag, or, if that ordering isn't possible, have the CMP's own consent-update callback call optima.consent.setGCM({...}) directly instead of relying on the dataLayer interception.
Consent-gated third-party scripts (tracker gating)
Mark a third-party tag with type="text/plain" and a data-optima-tracker name instead of loading it directly:
<script type="text/plain" data-optima-tracker="ga4" src="https://www.googletagmanager.com/gtag/js?id=G-XXXX"></script>
<script type="text/plain" data-optima-tracker="hotjar">
(function(h,o,t,j,a,r){ /* ... */ })(window, document);
</script>On load the SDK fetches GET /edge/v1/trackers once (browser-cached), joins each tag's data-optima-tracker name to its configured purpose, and — the instant that purpose is granted — clones the tag into a real <script> (carrying src, inline text, async, defer, nonce, crossorigin, integrity) right after the placeholder, and marks the placeholder data-optima-activated="1" so it's never activated twice. optima.consent.can("hotjar") answers the same question in code.
With a nonce-based CSP, give every placeholder the page's nonce (<script type="text/plain" nonce="…" data-optima-tracker="ga4" …>). Once the SDK knows a trusted nonce — display.scriptNonce, which defaults to the nonce of the <script> that loaded optima.js — it activates only placeholders that carry it. Any other placeholder is marked data-optima-rejected="nonce" and reported as tracker:error with error: "nonce_mismatch". Under 'strict-dynamic' the scripts the SDK creates are trusted whatever their source, so this check is what stops injected markup from borrowing that trust.
The SDK only derives that nonce by itself when optima.js is loaded by a <script> tag carrying the nonce. In every other setup the check stays off until you configure it:
- npm / bundlers (ESM): there is no loading tag to read a nonce from, so set
display.scriptNonceexplicitly. - A loader inserted by another script (an async snippet or tag manager doing
createElement('script'), the usual'strict-dynamic'pattern): the inserted tag has no nonce, so setdisplay.scriptNonceexplicitly. - A hash-based
'strict-dynamic'CSP (no nonce at all): placeholders cannot be told apart from injected markup. Don't usetext/plainplaceholders there; use managed tags (below) instead.
Revocation cannot unload an already-running script: withdrawing a previously granted purpose fires consent:revoked with { purposes: [...] } so the site can react — a full page reload is the honest way to actually stop a script that already loaded.
Managed tags
The same GET /edge/v1/trackers inventory can also carry tags authored entirely in the console — no placeholder markup on the page at all — for tags the site's own developers don't own. Each row's kind says how the SDK builds it:
script—createElement("script")withsrc,async(defaulttrue),defer, and an operator allowlisted set ofattributes, appended to<head>. Fires once per document.pixel—new Image()whosesrchas{{url}}(the current page URL, percent-encoded) and{{ts}}(Date.now()) substituted. Fires once per page view — an SPA route change (seespa: trueand SPA navigation) clears pixel bookkeeping so it fires again on the next view;script/htmltags never re-fire once they've run.html— runs through the same code runner as unstructured content (runInline: an inert<template>parse, then script re-creation) into a<div data-optima-tag="name">appended to<body>. Nevereval/new Function— a nonce-basedscript-srcCSP still works by settingdisplay.scriptNonce, which every managed script/html tag picks up the same waycontent.*does.page(or a row with nokind) is the placeholder behaviour above, unchanged.
A managed tag only ever runs when it is active, its purpose is granted, and the current URL matches its url_patterns (same glob syntax as content targeting — * matches within a path segment, no cross-slash wildcard). Patterns are matched against the whole URL, including scheme and host, minus the fragment — write https://shop.example/checkout/*, not */checkout (the scheme's // is itself two slashes, so a leading * can't cross it). As with placeholder tracker gating, revocation can't unload a tag that already fired — only a page reload does that.
Two events cover both placeholder and managed tags:
tracker:fired{ name, kind }— a tag ran successfully.tracker:error{ name, kind, error }— a runner threw; the SDK always catches it, so this event (plus adebugwarning) is the only way to see it. A failing tag never breaks the rest of the page.
Consent banner
Not a separate API — it's the built-in renderer for the banner_consent item type. Presence in a slot's response means "ask this visitor now": the server has already decided whether to (re-ask days, policy change, undecided purposes), so the SDK just draws it, bypassing frequency/trigger entirely. It opens in two stages, like every mainstream CMP: title, body and three buttons — Accept all / Reject all / Manage — and the per-purpose rows plus Save appear once Manage is pressed (Manage is hidden when there is no purpose to manage). "Accept all" / "Reject all" / "Save" all call POST /edge/v1/consent with banner_id + lang via the SDK's own consent.set(...) — the frozen policy: {key, version} the server sent along with the banner is stored in the local consent state for reference, but is never sent back on the wire (the server already knows it from banner_id).
Per-language copy (payload.languages.<lang>, the shape the console's banner editor writes — flat strings):
{
title: string; body: string; // required in "default"
accept_all?: string; reject_all?: string; // button labels
manage?: string; save?: string; // stage-two reveal / post buttons
policy_link_text?: string; // the policy link's text; its href is layout.policy_url
object_label?: string; // suffix on a legitimate-interest row ("Object")
buttons?: { accept_all?, reject_all?, save? } // pre-1.1.2 nested form, still honoured as a fallback
}Each purpose_details entry may carry descriptions (language code → text, authored on the purpose in the console); the toggle text resolves exact tag → primary subtag → description → name, with the same lang the copy uses — and through the same lookup: both are trimmed and matched case-insensitively, so SK, sk-SK and sk all reach the sk entry.
payload.layout (opaque, SDK-interpreted, same idea as display):
{
position?: "bottom" | "top" | "modal" | "center" | "bottom-left" | "bottom-right"; // default "bottom"; "modal" = centred modal (the console's vocabulary)
style?: "bar" | "modal" | "card"; // default "modal" if blocking or position "modal", else "bar"
theme?: "light" | "dark" | "auto" | Record<string, string>; // a preset, or CSS custom properties — see below
policy_url?: string; // href of policy_link_text; http(s) only, otherwise no link
buttons?: { accept_all?: string; reject_all?: string; save? : string }; // fallback labels when a language names none
blocking?: boolean; // modal + focus-trapped + non-dismissible
links?: Array<{ label: string; href: string }>; // extra links after the policy link; non-http(s) hrefs are dropped
css?: string; // operator stylesheet, validated + stripped by the server, injected verbatim — see Theming
}Theming. The banner ships with default styling (readable text, inline checkbox rows, a primary "accept" button, outlined "reject"/"manage"/"save"). theme: "light" | "dark" picks a preset pair for the first two variables below and "auto" follows prefers-color-scheme at render time; a map sets custom properties directly — a bare name gets -- prepended:
| variable | default | what it paints |
|---|---|---|
--optima-bg | #1a1a1a | the overlay item's background (bar / modal / card) |
--optima-fg | #fff | text, checkbox and button outlines |
--optima-accent | --optima-fg | the "accept all" button fill, checkbox accent, focus ring |
--optima-accent-fg | --optima-bg | the "accept all" button's text |
Every --optima-* property is set on both the .optima-consent root and the overlay wrapper around it (the wrapper is where --optima-bg/--optima-fg are actually read, and custom properties only inherit downward); any other name stays on the root for your own CSS. Class hooks for going further: .optima-consent (+ --expanded once Manage was pressed), __title, __body, __purposes, __purpose, __purpose-label, __links, __actions, __accept, __reject, __manage, __save — plus the overlay's .optima-overlay__item--{bar|modal|card} for the container.
Custom stylesheet. A layout.css string authored in the console (validated at save to reach only .optima-consent / .optima-overlay / #optima-overlay selectors; @media, @supports, @font-face, @keyframes; https:/data: URLs; served with comments stripped) is injected as one <style id="optima-consent-css-<item id>"> in <head>, after the SDK's own #optima-overlay-style — so an operator rule at equal specificity wins over the default without !important. It carries display.styleNonce, is replaced on redelivery, and is removed with the banner. One thing a custom sheet cannot do: reveal stage two early — the SDK's own .optima-consent [hidden] { display: none !important } keeps the purpose rows and Save collapsed until Manage, whatever display your rules give .optima-consent__purposes for the expanded state. One gotcha with the variables above: a custom sheet cannot set --optima-bg/--optima-fg by targeting .optima-consent, because those two are read on the overlay wrapper — an ancestor of the banner root, and only the inline layout.theme values are hoisted onto it. Target .optima-overlay__item instead: .optima-overlay__item { --optima-bg: #fff; --optima-fg: #1a1a1a }.