Sebastian Gomez
"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>.
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 withNotAllowedError(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 Token | Chrome Web Status |
|---|---|---|
LanguageModel | language-model | Stable Chrome 148+ |
Summarizer | summarizer | Stable Chrome 138+ |
Translator | translator | Stable Chrome 138+ |
LanguageDetector | language-detector | Stable Chrome 138+ |
Proofreader | proofreader | Developer 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.
Two rules govern this boundary:
- Strict intersection between HTTP header and
<iframe allow>: effective permission inside the child frame is the intersection of the parent's HTTPPermissions-Policyresponse header and theallowattribute on the<iframe>tag. An embedded frame can never grant itself an API that the parent host denied in its HTTP header. - Why Built-in AI still skips Web Workers: this same policy requirement answers a recurring performance question.
LanguageModel,Summarizer,Translator,LanguageDetector, andProofreaderremain unsupported inside Web Workers because workers lack a responsible document against which Chrome can evaluatePermissions-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.
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.
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:
- Zero eager
create()on load: never callcreate()insideDOMContentLoaded,useEffect(..., []), orngOnInit. - 4-state
availability(opts)probing: feature-detect'API' in self, handle all four availability states explicitly, and pass identical options toavailability()andcreate(). navigator.userActivation.isActivegate: verify an active user click before downloads and avoid long chainedawaitcalls that let transient activation expire.- Normalized
downloadprogressUI: wiremonitor(m)withMath.round(e.loaded * 100), handle Chromium's0% → 90% → 100%phases, and support download cancellation viaAbortController. - Cancelable streaming via
AbortController: propagate{ signal }tocreate()andpromptStreaming(), keep partial output onAbortError, and skip red error banners for user cancellation. - Deterministic VRAM/RAM cleanup and XSS safety: wrap every session (and every
baseSession.clone()task) intry/finally { session?.destroy(); }, hook BFCache-safepagehide, and render output withtextContentorstreaming-markdownplus the Sanitizer API /DOMPurify. - Explicit cross-origin policy: declare HTTP
Permissions-Policyheaders and<iframe allow="...">per token and exact origin (no*), diagnose withallowsFeature(), and validateevent.sourceplusevent.originonpostMessage.
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
- Interactive Demo 01 (6-API
availability()board): model-concierge.html - Interactive Demo 02 (Streaming +
AbortController+destroy()): stream-garden.html - Interactive Demo 03 (
Permissions-Policyacross:8080and:8081): iframe-passport.html - Full interactive talk deck (20 slides, ES/EN): slides-lifecycle/index.html
- Built-in AI Lifecycle Auditor Prompt (talk giveaway): GIST-READY-built-in-ai-lifecycle-auditor.md
- Official documentation: Control browser features with Permissions Policy · The Prompt API · MDN · MDN · MDN
Sebastian Gomez
Creador de contenido principalmente acerca de tecnología.