Ver en Español
"It Works in My Tab, Not in the Iframe": Permissions-Policy and Cross-Origin Delegation for Local AI in Chrome
Dec 01, 2026
Updated: Dec 01, 2026

"It Works in My Tab, Not in the Iframe": Permissions-Policy and Cross-Origin Delegation for Local AI in Chrome

In a top-level tab, LanguageModel runs without a single error. The moment a partner portal or micro-frontend embeds that exact page inside a cross-origin <iframe>, availability() flips to 'unavailable' and create() rejects with NotAllowedError.

Gemini Nano did not crash, and your session lifecycle code (Parts 1 and 2 of this series) did not break. You hit a deliberate browser security boundary.

Silent Denial by Design: Why the Default Allowlist Is self

Every Chrome Built-in AI API ships with a default allowlist of self. It works in top-level windows and same-origin frames, and denies access by default inside any cross-origin <iframe>.

meme-iframe-blocked.jpg

The failure mode misleads teams who have not hit it before:

  • Inside an undelegated cross-origin <iframe>, LanguageModel.availability() resolves silently to 'unavailable', looking identical to a machine missing a GPU or short of the 22 GB free disk floor.
  • If your code calls LanguageModel.create() anyway, Chrome rejects with NotAllowedError (DOMException).

Without an explicit policy check, your logs blend misconfigured partner embeds into the same bucket as unsupported client hardware.

Permission Intersection, Per-API Tokens, and the Web Worker Limit

Chrome governs cross-origin access via Permissions-Policy, giving each Built-in AI API its own token:

Global API (self[name])Permissions-Policy TokenChrome Web Status
LanguageModellanguage-modelStable Chrome 148+
SummarizersummarizerStable Chrome 138+
TranslatortranslatorStable Chrome 138+
LanguageDetectorlanguage-detectorStable Chrome 138+
ProofreaderproofreaderDeveloper trial (#proofreader-api)

Granular tokens preserve least privilege: a host app can grant translator or summarizer to an embedded support widget without exposing open-ended Prompt API access through language-model.

iframe-policy-boundary.gif

Two rules govern this boundary:

  1. Strict intersection between HTTP header and <iframe allow>: effective permission inside the child frame is the intersection of the parent's HTTP Permissions-Policy response header and the allow attribute on the <iframe> tag. An embedded frame can never grant itself an API that the parent host denied in its HTTP header.
  2. Why Built-in AI still skips Web Workers: this same policy requirement answers a recurring performance question. LanguageModel, Summarizer, Translator, LanguageDetector, and Proofreader remain unsupported inside Web Workers because workers lack a responsible document against which Chrome can evaluate Permissions-Policy.

HTTP Header, <iframe allow>, and Zero-Download Runtime Inspection

Safe cross-origin delegation between a host page and a trusted embed takes three explicit layers:

# 1. Host HTTP response header (name exact origins; avoid *)
Permissions-Policy: language-model=(self "https://widget.example.com"), summarizer=(self)

On routes that do not use local AI and should block every embed, turn the feature off with Permissions-Policy: language-model=(). Avoid the * wildcard in production, which delegates the API to every embedded origin.

One deployment constraint to catch early: static hosts such as GitHub Pages (.nojekyll) do not support custom HTTP response headers like Permissions-Policy. If your host runs behind Cloudflare Pages (_headers), Netlify (netlify.toml), Vercel (vercel.json), or Nginx, declare the exact allowed HTTPS origins there.

<!-- 2. Explicit iframe delegation in parent HTML -->
<iframe
  src="https://widget.example.com/embed.html"
  allow="language-model"
  title="Embedded AI assistant"
></iframe>

<!-- Multiple APIs separated by semicolons -->
<iframe
  src="https://widget.example.com/embed.html"
  allow="language-model; summarizer; translator"
  title="Multi-API widget"
></iframe>

<!-- Explicitly deny even a same-origin iframe -->
<iframe
  src="/local-sandbox.html"
  allow="language-model 'none'"
  title="Sandboxed frame without local AI"
></iframe>
// 3. Runtime policy check inside the iframe (zero model download)
// Defensive fallback: Chrome Stable exposes document.featurePolicy;
// document.permissionsPolicy is still behind experimental platform flags.
const policy = document.permissionsPolicy || document.featurePolicy;
const allowed = policy?.allowsFeature ? policy.allowsFeature('language-model') : null;

// From the parent page inspecting a specific <iframe> element:
const frameAllowed = iframeEl.featurePolicy?.allowsFeature('language-model');

That third snippet pays off quickly in support queues. Inside the embedded frame, allowsFeature('language-model') reports in under a millisecond whether Permissions-Policy blocked access—without calling create() or downloading a single megabyte. On the parent page, iframeEl.featurePolicy?.allowsFeature('language-model') verifies that a specific frame received the expected delegation before mounting the widget UI. Your logs cleanly distinguish an integration error (allowed === false) from unsupported hardware.

Live Walkthrough: Two Real Origins (:8080 ⇄ :8081) in Iframe Passport

To reproduce a real cross-origin boundary locally without external servers, this repository includes scripts/serve.py, which runs http://localhost:8080 and http://localhost:8081 side by side for Demo 03 · Iframe Passport. Opening the file over file:// lacks a Secure Context and HTTP origins, so the demo shows a banner pointing you to npm run serve.

First, load the iframe-probe.html frame on :8081 without an allow attribute: the passport stamp turns red (DENIED · NO DELEGATION) and the JSON payload returns "languageModelPolicyAllowed": false. Toggle the checkbox to inject allow="language-model" and reload the probe: the stamp turns green (ALLOWED · PERMISSIONS-POLICY OK) and the JSON switches to "languageModelPolicyAllowed": true while keeping "inferenceRequested": false.

demo-iframe-passport-policy.gif

The static capture below with delegation enabled makes the :8080 ⇄ :8081 boundary easy to inspect in full: the generated <iframe ... allow="language-model"> markup, the untruncated Permissions-Policy HTTP header ready to copy, the tilted green AUTORIZADO stamp, and the second-origin JSON payload returned with zero inference triggered.

demo-iframe-passport-ui.png

Cross-origin messaging between the probe (demos/iframe-probe.html) and the host (demos/assets/lifecycle.js) skips unsafe shortcuts too. The probe derives its postMessage target origin from document.referrer instead of broadcasting to '*'. On the receiving side, demos/assets/lifecycle.js enforces event.source === frame.contentWindow and verifies exact origin equality via Origin.from(event) with a new URL(event.origin) fallback (always rejecting 'null' origins) before rendering the JSON:

// demos/iframe-probe.html (simplified)
const policy = document.permissionsPolicy || document.featurePolicy;
const allowed = policy?.allowsFeature ? policy.allowsFeature('language-model') : null;
const report = {
  kind: 'ai-policy-probe',
  origin: location.origin,
  secureContext: isSecureContext,
  languageModelExposed: 'LanguageModel' in self,
  languageModelPolicyAllowed: allowed,
  inferenceRequested: false,
};
if (parent !== self && document.referrer) {
  const targetOrigin = new URL(document.referrer).origin;
  if (targetOrigin !== 'null') parent.postMessage(report, targetOrigin);
}
// demos/assets/lifecycle.js — strict parent postMessage verification
addEventListener('message', (event) => {
  const frame = document.querySelector('#probe');
  if (event.source !== frame.contentWindow || event.data?.kind !== 'ai-policy-probe') return;
  const senderOrigin = new URL(event.origin).origin;
  const expectedOrigin = new URL(frame.src).origin;
  if (senderOrigin === 'null' || senderOrigin !== expectedOrigin) return;
  renderPolicyReport(event.data);
});

A 7-Point PR Checklist and the Lifecycle Auditor Prompt

Everything across all three parts comes down to seven concrete checks before approving a Chrome Built-in AI pull request:

  1. Zero eager create() on load: never call create() inside DOMContentLoaded, useEffect(..., []), or ngOnInit.
  2. 4-state availability(opts) probing: feature-detect 'API' in self, handle all four availability states explicitly, and pass identical options to availability() and create().
  3. navigator.userActivation.isActive gate: verify an active user click before downloads and avoid long chained await calls that let transient activation expire.
  4. Normalized downloadprogress UI: wire monitor(m) with Math.round(e.loaded * 100), handle Chromium's 0% → 90% → 100% phases, and support download cancellation via AbortController.
  5. Cancelable streaming via AbortController: propagate { signal } to create() and promptStreaming(), keep partial output on AbortError, and skip red error banners for user cancellation.
  6. Deterministic VRAM/RAM cleanup and XSS safety: wrap every session (and every baseSession.clone() task) in try/finally { session?.destroy(); }, hook BFCache-safe pagehide, and render output with textContent or streaming-markdown plus the Sanitizer API / DOMPurify.
  7. Explicit cross-origin policy: declare HTTP Permissions-Policy headers and <iframe allow="..."> per token and exact origin (no *), diagnose with allowsFeature(), and validate event.source plus event.origin on postMessage.

If you want to run that audit automatically on any stack, copy the Built-in AI Lifecycle Auditor Prompt. It inspects your repository in read-only mode against all seven anti-patterns, draws an explicit FSM, outputs a drop-in ai-lifecycle-guard.js plus Permissions-Policy configuration, and includes a Node.js verifier (validated at 18/18 static and runtime checks against this repository in sample-audit-report.md).

Before shipping any local-AI embed to a partner portal, test it across two local ports (npm run serve on :8080 and :8081), verify allowsFeature() both with and without allow, and confirm in your test harness that created === destroyed on teardown.

Live Lab and References

Sebastian Gomez

Sebastian Gomez

Creador de contenido principalmente acerca de tecnología.

Leave a Reply

0 Comments

Advertisements

Related Posts

Categorías