# 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.

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

CookieConsent manages `<script>` tags and nothing else. It has no convention for iframes, so consent-kit brings its own:

1. At build time, `consentEmbed` writes an inert `<div data-ck-embed ...>` where the iframe would go. It carries the URL in `data-src`, so the browser requests nothing.
2. In the browser, `syncEmbeds` looks 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

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:

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

```sh
npx consent-kit build
```

The fields are described in the [registry reference](/docs/manual/reference/registry/).

## 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:

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

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

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

```ts
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

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:

```ts
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

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:

```ts
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

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

```css
[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

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

**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:4174
```

The 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](/docs/manual/reference/content-security-policy/).

**The guard.** The iframe is in the guard manifest with its declared prefix, category and service:

```json
{
  "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](/docs/manual/reference/runtime-api/#the-guard).

**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:

```sh
npx consent-kit audit http://localhost:4173 --page / --page /video.html
```

If 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](/docs/manual/reference/audit/).

## Limits

- **One consent purpose per iframe.** `consentEmbed` throws 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 through `consentEmbed`.
- **Only `src` and `title` are set.** `syncEmbeds` does not set `allow`, `allowfullscreen`, `sandbox`, `loading` or 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](/docs/manual/concepts/threat-model-and-limits/).
