Skip to content
Optima docs
SDKsJavaScript SDK

Content

JavaScript SDK v1.4.0 — Content

The display engine (slots, the consent banner, campaign on-site surfaces) is a lazy chunk — dist/display.js, ≤ 12 KB gzip, loaded via a dynamic import() the first time any of these happen: a content.* call, optima.content.slot(...) being declared, or a [data-optima-slot] element existing when the page finishes loading. The IIFE build resolves display.js next to wherever optima.js itself was actually loaded from (the loading <script>'s own src, falling back to <endpoint>/edge/v1/sdk/v1/display.js when that isn't available); bundler/ESM users can import { createDisplay } from "@optima/sdk" directly instead if they'd rather drive their own code-splitting.

That dynamic import() is a normal browser module fetch, so when the bundle and the display chunk are served from a different origin than the host page: the host's script-src CSP directive needs that origin allowlisted (module import() is subject to the same script-src as the initial <script> tag), and the gateway serving display.js needs to answer the browser's CORS preflight for it (Phase 5 serves display.js next to optima.js with that in mind). Same-origin hosting (the common case — the gateway serves the page too, or optima.js is proxied under the host's own domain) needs neither.

Slots

Declare a slot in markup or in code — either way, the SDK fetches GET /edge/v1/content?slot=... for it on load and on SPA navigation:

<div data-optima-slot="homepage_hero"></div>
optima("content.slot", "homepage_hero"); // or, once loaded: optima.content.slot("homepage_hero")

An item bound to a slot element renders inline, appended into it. An item declared with no element — optima.content.slot("promo") with no el, or any item the server marks payload.display.placement: "overlay" — renders in the SDK's single, page-topmost overlay layer instead.

Rendering, by item type: banner_consent is the built-in consent banner (Consent banner); structured banner gets the built-in {title, body, image_url, cta_label, cta_url} template; any other structured type goes to a renderer registered with content.register(type, (item, el) => ...), or — absent one — is emitted as a content:item event and drawn nothing (never thrown); unstructured items run through the code runner (below) — they are operator-authored HTML/CSS/JS, executed, not treated as a template.

A served campaign entitlement (origin: "campaign", a token) reports impression once ≥ 50% visible for 1 s, click on activation, and dismiss on close — batched to POST /edge/v1/content/events, flushed on pagehide/tab-hide same as the tracker outbox. display.stop_on_click (server-authored) hides the item after a click is reported, without a separate dismiss.

display schema (payload.display)

The server passes this object through verbatim — it's entirely SDK-interpreted:

{
  placement?: "inline" | "overlay";         // default: inline if the slot has a bound element, else overlay
  position?: "bottom" | "top" | "center" | "bottom-left" | "bottom-right"; // default "bottom"
  style?: "bar" | "modal" | "card";          // default "card"
  trigger?: { on: "load" | "delay" | "scroll" | "exit" | "event"; delay_ms?: number; scroll_pct?: number; event?: string }; // default { on: "load" }
  frequency?: "always" | "session" | "once" | { per_days: number }; // default "always" inline, "session" overlay
  dismissible?: boolean;                     // default false inline, true overlay
  ttl_days?: number;                         // how long a dismissal is remembered before re-showing; omit for "forever"
}

Frequency and dismiss memory persist in localStorage/sessionStorage (see Storage) — a dismissed item never reappears (regardless of frequency) until ttl_days has elapsed since the dismissal, or never if omitted.

Anti-flicker

display.hideUntilReady: { selector, timeout_ms } (default timeout_ms 1500) injects a visibility:hidden style for selector as soon as the display chunk constructs, and removes it once the first refresh() settles or the timeout fires — whichever comes first, so a slow gateway response never leaves the page permanently hidden. Pair with display.styleNonce on a strict style-src CSP.

SPA navigation

A route change re-fetches every declared slot — whenever spa: true, whether or not page: "auto" is on (content is targeted by URL, so a host sending its own page() calls still needs the refresh). Inline slots are always cleared and redrawn (their own frequency rule, not DOM presence, decides whether an item comes back); an overlay item still on screen from a previous response that the new one no longer includes for its slot just disappears — silently, with no dismiss report and no dismiss memory recorded, because it stopped being served rather than being dismissed by the visitor. A slower, now-stale response from an earlier navigation is discarded outright. Only a real URL change counts: a pushState/replaceState that leaves location.href unchanged (hydration, scroll restoration) triggers no page view, no content refresh and no pixel re-fire.

Web personalization

Server-rendered; the SDK only applies. A web_personalization item is campaign-only (origin: "campaign", a token) and applies immediately on every refresh() — no rule/trigger/frequency gate, the server already decided eligibility. It's either:

  • {payload: {modifications: [{selector, op, value?, attr?}]}} — the applier runs each op (set_html → innerHTML, set_text → textContent, hide → adds a class with display:none, set_attr → setAttribute(attr, value)) and retries any selector with no match through a MutationObserver for up to 3 s, so late-rendering frameworks still get modified; or
  • {format: 'unstructured', html} — an HTML fragment run through the code runner's inline mode (below), so a <script> in it executes.

Reports one impression the moment something actually lands on the DOM (immediate match, a late MutationObserver match, or the fragment append — never when every selector times out unmatched). A route change undoes every applied modification for that slot (restoring the previous innerHTML/textContent/attribute/class; a fragment's own script side effects are not reversed) before the slot's items are re-fetched.

Custom code run and the trust model

unstructured display items and web_personalization fragments are operator-authored code, executed on the customer's site — that's the product ("custom code run"), and the trust boundary is the tenant: only an authenticated console user with content_editor can author it, and the gateway only ever serves it to keys of the same tenant. The SDK does not sanitize this HTML; it only decides how it runs:

  • inline mode (display.codeMode: "inline", the default): the document is parsed inertly, its nodes appended to the slot element (or the overlay layer / document.body for a personalization fragment), and every <script> re-created so the browser actually executes it (innerHTML never runs a <script>). Scripts get full page access — what a tag manager gives. External src scripts load asynchronously but execute in document order, same as a normally parsed page.
  • sandbox mode (display.codeMode: "sandbox"): the item renders in a zero-chrome <iframe sandbox="allow-scripts"> instead — no page access, no cookies — auto-sized to its content. The right default for a tenant under regulatory constraints. web_personalization fragments always run inline; the sandbox choice is for display items only. A sandboxed item's plain clicks are not visible to the SDK — no click report, and display.stop_on_click has no effect on them, since the SDK has no visibility into an opaque-origin iframe's DOM; only the declarative data-link/data-actiontype actions (below) get out of the frame. Impression reporting (dwell-based, from the outside) still works; anything requiring in-content interaction tracking should use inline mode instead.
  • Declarative actions (both modes, same markup as the Android/iOS SDKs): an element — or any ancestor of the clicked element — carrying data-actiontype="close" dismisses the item through the normal dismiss path (dismiss memory honouring ttl_days, a dismiss report for campaign items, the nodes/overlay entry removed); one carrying data-link="<url>" (optionally with data-actiontype="browser" or "deeplink", treated identically) reports a click for campaign items (then honours display.stop_on_click) and navigates with location.assign. The nearest matching ancestor wins, and close beats data-link on the same element. Only absolute http(s): URLs and app schemes (myapp://…, tel:, mailto:) are followed — javascript:, data:, file:, vbscript:, blob:, about: and relative URLs are ignored. Both are preventDefault()ed (and stop propagating); plain <a href> links keep their normal behaviour. A close on an inline item counts as a dismissal too, even though inline items default to non-dismissible with always frequency: the dismiss memory is checked before the frequency, so the next refresh on the same page (and later ones) does not redraw it until ttl_days has elapsed — permanently when the item carries none. In sandbox mode the frame's injected bootstrap posts {optima:"close"} / {optima:"link", url} to the host, which accepts them only from that frame's own contentWindow.
<div class="promo">
  <button data-actiontype="close" aria-label="Close">×</button>
  <div data-link="https://shop.example.com/sale" data-actiontype="browser">Shop the sale</div>
</div>
  • Customer CSP: a site with a strict script-src blocks re-created inline scripts — in both inline and sandbox mode, since a srcdoc iframe inherits the embedding page's CSP. The SDK detects the resulting securitypolicyviolation for its own nodes and emits content:blocked ({itemId?, blockedURI, directive}) so you can see it, rather than a campaign silently losing its custom code. The one real remedy is a nonce: propagate display.scriptNonce (applied to every re-created <script>) if the site's CSP is nonce-based, or ask the operator to relax script-src for known-safe sources. codeMode: "sandbox" doesn't help with a CSP block — choose it for page-access/cookie isolation instead. content:blocked can also fire for a CSP violation the SDK had nothing to do with (the host page's own blocked resource) — treat itemId: undefined as "not necessarily ours", not as a guaranteed code-run failure.
optima.on("content:blocked", ({ itemId, blockedURI, directive }) => {
  console.warn(`optima content blocked by CSP: item=${itemId} directive=${directive} uri=${blockedURI}`);
});

On this page