Previewing AI-Written Pages Without Opening a Security Hole

Chat apps that show a live preview of the code a model just wrote feel magical: ask for a timer, a chart or a small game and it appears next to the conversation. When that preview fails to render, as users of some desktop apps report for weeks at a time, people suddenly realise how much they relied on it. Builders of hobby chatbots want the same feature in their own projects, and the obvious approach, inserting the model's HTML into the page, is also the most dangerous one.
This guide is for developers who want to display model-generated HTML, SVG or small JavaScript apps inside their own web app. You will learn the threat model in plain terms, how to use a sandboxed iframe correctly, when to sanitise instead, how to handle Markdown answers, and how to debug a preview that stays blank. The examples call the keyless OpenAI-compatible API on this site, but nothing depends on a particular model.
Frequently asked questions
Why is inserting model HTML into my page dangerous?
The model's output can contain scripts or event handlers, either by accident or because a prompt injection asked for them. Inserted into your page, that code runs with your site's privileges and can read cookies, tokens or user data.
What is a sandboxed iframe?
It is an iframe with the sandbox attribute, which puts its content in a restricted environment. Without extra permissions it cannot run scripts, submit forms or access the parent page, and you can grant only the capabilities you need.
How does sanitising differ from sandboxing?
Sanitising removes dangerous tags and attributes so the remaining HTML can sit safely in your page. Sandboxing keeps the content separate and lets it run, but isolated. Use sanitising for formatted text and sandboxing for interactive previews.
Which is better for rendering Markdown answers?
Convert Markdown to HTML with a library, then sanitise the result before inserting it. That covers headings, lists, tables and code blocks without allowing scripts.
Can I allow scripts in the sandbox safely?
Yes, if you do not also allow same-origin. Scripts then run in an opaque origin with no access to your cookies or storage. Combining allow-scripts with allow-same-origin removes most of the protection.
Why does my preview show a blank frame?
Common causes are a strict Content Security Policy, a missing doctype, a script that throws on load, blocked external resources, or the model returning code wrapped in Markdown fences that you did not strip.
Does the model output need to be trusted at all?
No, and that is the point. Treat every model response as untrusted input, like text from an anonymous user, regardless of which model produced it.
- The threat model in plain terms
- Get clean code out of the model first
- Render interactive previews in a sandboxed iframe
- Sanitise formatted answers that live in your page
- Add a Content Security Policy
- Debugging a preview that stays blank
- Handling rate limits and errors in the UI
- Choosing a model for page generation
Step by step
- Request a self-contained document — Ask the model for one complete HTML file with inline CSS and JavaScript and no external URLs, wrapped in an html code block.
- Extract the code — Take the content between the html fence and the closing fence, and check that the document ends properly.
- Render in a sandbox — Create an iframe with sandbox set to allow-scripts only, and assign the HTML to srcdoc.
- Sanitise ordinary answers — Convert Markdown to HTML with a library and pass it through a sanitiser before inserting it into your page.
- Add a policy and test — Set a strict Content Security Policy, then test with several generated pages and check the console for violations.
The threat model in plain terms
A model writes whatever text best fits the conversation. Most of the time that is harmless. But conversations can include untrusted content: a web page the model summarised, a document a user uploaded, a message from another user in a shared chat. Any of these can contain instructions that steer the model into emitting code that steals data. You cannot reliably prevent that at the model level, so you must contain it at the rendering level.
The rule is the same one web developers have used for decades: never insert untrusted HTML into your page without either sanitising it or isolating it. Model output is untrusted, whichever vendor produced it.
Cookie and token theft
A script running in your origin can read non-HttpOnly cookies, local storage and in-memory tokens, then send them anywhere.
Phishing inside your UI
Even without scripts, injected HTML can draw a fake login form that looks like part of your app. Isolation makes that form visually and technically separate.
Get clean code out of the model first
Ask the model for a complete, self-contained HTML document with inline CSS and JavaScript and no external resources. That makes previews reliable and keeps the sandbox simple. Models often wrap code in Markdown fences, so extract the content between the first ```html and the closing fence before rendering.
The snippet below requests a small page from the keyless endpoint and extracts it. Keep max_tokens generous so the document is not cut off; a truncated page is a frequent cause of blank previews.
Ask for no external resources
Inline everything. External scripts and fonts may be blocked by your policy or by the sandbox, and they also let the generated page call home.
async function generatePage(idea) {
const res = await fetch("https://api.apifreekeyanthropic.com/v1/chat/completions", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
model: "free-ai",
max_tokens: 3000,
messages: [
{ role: "system", content: "Return one complete HTML document with inline CSS and JS. No external URLs. Wrap it in a ```html code block." },
{ role: "user", content: idea }
]
})
});
const data = await res.json();
const text = data.choices[0].message.content || "";
const match = text.match(/```html\s*([\s\S]*?)```/i);
return match ? match[1] : text;
}
Render interactive previews in a sandboxed iframe
For anything that should run, like a game, a calculator or a chart with JavaScript, use an iframe with the sandbox attribute and put the HTML in srcdoc. Grant allow-scripts so the code works, and do not grant allow-same-origin. The frame then runs in a unique opaque origin: it cannot read your cookies, your local storage or the parent document.
Avoid granting extra capabilities unless you need them. Forms, pop-ups, top-level navigation and downloads each have their own sandbox token, and each widens what the generated code can do.
Why not allow-same-origin?
With both scripts and same-origin allowed, code inside the frame can reach the parent page and even remove its own sandbox. That combination defeats the purpose.
A separate preview domain
Larger apps serve previews from a different domain entirely. That adds a second layer of isolation, so even a sandbox misconfiguration cannot touch your main site's cookies.
function showPreview(container, html) {
const frame = document.createElement("iframe");
frame.setAttribute("sandbox", "allow-scripts"); // no allow-same-origin
frame.setAttribute("referrerpolicy", "no-referrer");
frame.style.width = "100%";
frame.style.height = "420px";
frame.style.border = "1px solid #ccc";
frame.srcdoc = html;
container.replaceChildren(frame);
}Sanitise formatted answers that live in your page
Ordinary chat answers with bold text, lists and tables do not need a sandbox, but they do need sanitising before insertion. Convert Markdown with a maintained library, then pass the HTML through a sanitiser such as DOMPurify, which strips scripts, event handlers and dangerous URLs while keeping safe formatting.
Never write your own regex-based sanitiser. HTML parsing has countless edge cases, and attackers know them all. A maintained library is updated when new tricks are discovered.
Sanitise after Markdown conversion
Markdown can contain raw HTML. Sanitising the Markdown source is not enough; sanitise the HTML that comes out of the converter.
- Allow: paragraphs, headings, lists, tables, code, links with http and https URLs.
- Strip: script, style, iframe, object, embed and any on-event attribute.
- Rewrite links: open in a new tab with
rel="noopener noreferrer". - Escape code blocks: show code as text, never execute it.

Add a Content Security Policy
A Content Security Policy tells the browser what your page may load and execute. A strict policy on your main app blocks inline scripts and unexpected domains, which is exactly what you want as a backstop if a sanitiser ever misses something. It also governs srcdoc frames in some respects, which is a common reason previews break after a security hardening.
Test your policy with real generated pages. If previews stop working, check the browser console for policy violations before blaming the model; the message usually names the blocked directive.
Frame-specific policy
You can include a meta CSP tag inside the generated document before rendering, limiting the preview further, for example blocking all network requests with connect-src 'none'.
Debugging a preview that stays blank
When a preview does not render, work through the causes in order of likelihood. First check whether the HTML you passed is complete: a missing closing tag at the end usually means the output was truncated by max_tokens. Then check whether you stripped the Markdown fence. Then open the browser console for script errors or policy violations from inside the frame.
Desktop chat apps that fail to render previews often have similar causes underneath: a graphics or webview component issue, a cache problem, or a policy blocking embedded content. In your own app you at least have full access to the console, which makes these issues quick to diagnose.
Use a Blob URL for big pages
Create a Blob from the HTML with type text/html, make an object URL from it and set it as the frame's src while keeping the sandbox attribute. Revoke the URL when the preview closes so memory is released.
- Truncated output: raise
max_tokens, or ask for a shorter page. - Fence not stripped: the frame shows the raw backticks or nothing.
- Script error on load: the console inside the frame shows it.
- Blocked resources: the model ignored the instruction and used a CDN link.
- Size limits: very large srcdoc strings can fail in some browsers; write them to a Blob URL instead.

Handling rate limits and errors in the UI
Generating whole pages takes longer than a chat reply, and free endpoints have limits. The keyless API here allows one request per second with short bursts, two parallel requests and a daily cap per IP. It returns 429 with a Retry-After header when you exceed the rate, and 503 when it is busy, in which case retrying after two to five seconds is appropriate.
Show a clear state for each case rather than an empty frame. Streaming the response with server-sent events lets you display the code as it arrives, which reassures users that something is happening; the stream ends with data: [DONE]. Render the preview only once the full document has arrived.
Disable the button while generating
Preventing repeat clicks avoids burning requests and hitting the parallel limit by accident.
Keep the last good preview
If a new generation fails or is rate limited, leave the previous working preview on screen with a small notice, instead of replacing it with an empty frame. Users then never lose what already worked.
Choosing a model for page generation
Any capable model can produce simple pages. For complex interactive apps, top commercial models such as the Claude family are generally better at writing larger amounts of coherent, working JavaScript, and they handle iterative edits more reliably. This site is not affiliated with Anthropic, and free-ai is an independent open-weight model of about 35B parameters; it is fine for small widgets, demos and testing your rendering pipeline.
Whichever you use, the safety design here does not change. For guidance on keeping prompts small and testable, see one giant prompt versus small steps. And if you want to embed generated output inside Office documents rather than a web page, calling a chat API from an Office add-in covers that environment.
Iterate with diffs, not rewrites
When a user asks to change a generated page, send the current document back with a short instruction and ask for the full updated document. Comparing old and new versions lets you show what changed and roll back a bad edit with one click.

Send a first prompt from the chat box on the home page: no key, no account and no card, just your browser.
Read also
- Rolling Usage Window vs Fixed Daily Reset: Which Is Easier to Plan?
- Is It Okay to Build on an AI Service's Undocumented Endpoints?
- Why Do Agent Benchmarks Contradict the Usual Model Rankings?
- Why Does an AI Agent Keep Asking Permission Instead of Working?
- Why Can a Bigger Model Use Fewer Tokens on the Same Big Task?