Beta. consent-kit is at 0.x: expect breaking changes between releases, and treat everything it generates as a draft. Report a problem or share feedback.
Embed an iframe behind consent
This guide puts a third-party iframe, such as a video player, on a page so that nothing loads from the vendor until the visitor agrees. You declare the iframe in the registry, write a placeholder at build time with consentEmbed, and swap in the real iframe in the browser with syncEmbeds.
The example is the video page of examples/static-site.
How it works
Section titled “How it works”CookieConsent manages <script> tags and nothing else. It has no convention for iframes, so consent-kit brings its own:
- At build time,
consentEmbedwrites an inert<div data-ck-embed ...>where the iframe would go. It carries the URL indata-src, so the browser requests nothing. - In the browser,
syncEmbedslooks at every such placeholder. Where the visitor has accepted the placeholder’s category, it appends the iframe. Where consent was withdrawn, it removes the iframe again.
1. Declare the iframe
Section titled “1. Declare the iframe”An iframe is an iframe artefact with a src, a processor and a purpose. The example site declares a consent purpose for embedded video, the vendor, and the iframe:
purposes: - id: media version: 1 basis: consent default: denied title: en: Embedded video description: en: Loads the video player from Acme Video, which then receives your IP address. dataCategories: [ip_address] retention: session automatedDecisionMaking: false dataSubjects: [visitors]
processors: - id: acme-video name: Acme Video legalEntity: Acme Video GmbH country: DE
artefacts: - id: acme_video_embed kind: iframe src: http://127.0.0.1:4174/embed processor: acme-video purposes: [media]src is an origin or a URL prefix. Declare the part every embed shares, for example the player path without the video id. The concrete URL can be given per embed in step 2.
Bind the iframe to exactly one consent purpose. consentEmbed refuses an iframe that is bound to several.
The address in the example is a local fake vendor. A real registry declares an https: URL.
Then build:
npx consent-kit buildThe fields are described in the registry reference.
2. Render the placeholder at build time
Section titled “2. Render the placeholder at build time”Call consentEmbed in the script that writes your HTML. This is what src/build.ts of the example does:
import { readFileSync } from 'node:fs';import { consentEmbed, parseRegistry } from '@consent-kit/cli';
const parsed = parseRegistry(readFileSync('privacy.registry.yaml', 'utf8'));if (!parsed.ok) throw new Error(`invalid registry: ${parsed.errors.map((e) => e.message).join('; ')}`);const registry = parsed.registry;
const videoVendor = registry.processors.find((p) => p.id === 'acme-video')?.name ?? 'a third party';const videoEmbed = consentEmbed(registry, 'acme_video_embed', { title: `${videoVendor} player`, placeholder: `<div><p>This video is provided by ${escapeHtml(videoVendor)}. Loading it sends your IP address to them.</p>` + '<button type="button" class="plain" data-embed-allow>Allow embedded video</button></div>',});escapeHtml is the build script’s own helper. consentEmbed escapes the attribute values it writes, but not the placeholder.
The page source, pages/video.html, has a marker that the build replaces with videoEmbed:
<h1>Video</h1><p>The player below comes from Acme Video. It only loads once you allow embedded video.</p>{{VIDEO_EMBED}}The HTML that ends up in the page:
<div data-ck-embed data-category="media" data-service="acme-video" data-src="http://127.0.0.1:4174/embed" data-title="Acme Video player"><div><p>This video is provided by Acme Video. Loading it sends your IP address to them.</p><button type="button" class="plain" data-embed-allow>Allow embedded video</button></div></div>The three options:
| Option | Meaning |
|---|---|
title |
The accessible name of the iframe. Always set it. |
src |
The concrete URL for this embed. It must be on the declared origin and under the declared path. Default: the declared src. |
placeholder |
HTML shown until the iframe loads. It is inserted as given, so escape anything that is not your own markup. |
To embed one video among many, pass its URL as src:
consentEmbed(registry, 'acme_video_embed', { title: 'Product tour', src: 'http://127.0.0.1:4174/embed/abc?autoplay=0',});A URL outside the declared prefix throws at build time. /embed covers /embed/abc but not /embedded.
Wrap the placeholder content in an element, as the example does with its <div>. syncEmbeds hides the placeholder’s child elements when the iframe loads; text placed directly inside the placeholder would stay visible.
3. Activate it in the browser
Section titled “3. Activate it in the browser”Call syncEmbeds whenever consent may have changed: from CookieConsent’s onConsent, which runs on every page load once a decision exists, and from onChange. From src/client/main.ts of the example:
import { cookieConsentAccepted, syncEmbeds } from '@consent-kit/storage';import { cookieConsentConfig } from '#consent/cookieconsent.config.gen.ts';
const isAccepted = cookieConsentAccepted();
void CookieConsent.run({ ...cookieConsentConfig, onConsent: () => void syncEmbeds(isAccepted), onChange: () => { syncEmbeds(isAccepted); },});syncEmbeds is idempotent. It loads an embed when its category is accepted and, because the placeholder names a service, when that service (the processor acme-video) is switched on inside the category. It returns { loaded, unloaded }.
If nothing calls syncEmbeds, the placeholder stays a placeholder.
The “allow” button
Section titled “The “allow” button”The placeholder is your markup, so a button in it does nothing by itself. The example gives its button the attribute data-embed-allow and handles the click by accepting the placeholder’s category in CookieConsent:
document.addEventListener('click', (event) => { const button = event.target instanceof Element ? event.target.closest('[data-embed-allow]') : null; const category = button?.closest<HTMLElement>('[data-ck-embed]')?.dataset.category; if (!category) return; const accepted = CookieConsent.getUserPreferences().acceptedCategories; CookieConsent.acceptCategory([...new Set([...accepted, category])]);});This is the same decision as ticking “Embedded video” in the preferences modal. CookieConsent records it and fires onChange, which calls syncEmbeds. The choice holds for every embed of that category on the site, and the visitor can undo it in the preferences.
4. Style it
Section titled “4. Style it”syncEmbeds creates a bare iframe with a src and a title. Size comes from your CSS. The placeholder has data-ck-embed="" before the iframe loads and data-ck-embed="loaded" after, and the iframe has the attribute data-ck-embed-frame. The example site uses:
[data-ck-embed] { aspect-ratio: 16 / 9; display: grid; place-items: center; text-align: center; padding: 1rem; }[data-ck-embed='loaded'] { padding: 0; }[data-ck-embed] iframe { width: 100%; height: 100%; border: 0; }Use a stylesheet, not style attributes: the generated Content-Security-Policy does not allow inline styles.
What the visitor sees
Section titled “What the visitor sees”Before any decision, and after a refusal: the placeholder with your notice and your button. No request goes to the vendor.
After accepting the category, in the banner, in the preferences or with your button: the notice is hidden and the player loads in its place.
After withdrawing: the iframe is removed and the notice is back.
What the other layers do
Section titled “What the other layers do”The Content-Security-Policy. The origin of the declared src is added to frame-src. For the example:
frame-src 'self' http://127.0.0.1:4174The policy is the same before and after consent, and it lists origins, not paths. It stops an iframe from an origin you did not declare. It does not hold a declared iframe back until consent. See the Content-Security-Policy reference.
The guard. The iframe is in the guard manifest with its declared prefix, category and service:
{ "id": "acme_video_embed", "name": "http://127.0.0.1:4174/embed", "categories": ["media"], "service": "acme-video"}The guard watches for <iframe src> elements entering the document. The iframe syncEmbeds inserts after consent matches this entry and is let through. An iframe to that URL inserted without consent, or an iframe to an undeclared third-party URL, is removed. In record mode an undeclared one is left in place and recorded. See the runtime API reference.
The audit. The audit sees an iframe as a frame navigation and matches it against the same manifest. The check “Grant activates exactly what is declared” expects to observe acme_video_embed after it grants media, so the audit has to visit the page with the embed:
npx consent-kit audit http://localhost:4173 --page / --page /video.htmlIf no audited page has the embed, the check reports the artefact as declared but not observed. If the iframe loads before consent, or after a refusal, the checks “Pre-consent silence” and “Reject means reject” report it as wrong-purpose. What the vendor’s page loads inside its own frame is not judged: that is the vendor’s page, not yours. See the audit reference.
Limits
Section titled “Limits”- One consent purpose per iframe.
consentEmbedthrows for an iframe bound to several consent purposes. An iframe bound to no consent purpose is returned as a plain<iframe src>that loads at once. - A hard-coded
<iframe>is not gated. If your HTML contains the iframe itself, only the guard stands between it and the vendor, and the guard acts after the element is inserted: the request may already have started. Always go throughconsentEmbed. - Only
srcandtitleare set.syncEmbedsdoes not setallow,allowfullscreen,sandbox,loadingor a size. - Withdrawal removes the frame, not the vendor’s data. A cross-origin iframe has its own cookies and storage on the vendor’s origin. Neither
syncEmbeds, the storage facade nor the guard can reach them. - The placeholder HTML is yours. It is not escaped and not checked.
- The embed is per category, not per video. Accepting loads every placeholder of that category and service on every page.
For what each layer can and cannot stop, see Threat model and limits.