HTML Live Preview: Test and Debug HTML Online
How Live Preview Works
An HTML live preview editor lets you write code on one side and see the rendered result instantly on the other. Under the hood, it uses an iframe with srcdoc or a dynamically written document. Every keystroke triggers a DOM update inside the iframe.
<iframe id="preview"></iframe>
<script>
const editor = document.getElementById('editor');
const preview = document.getElementById('preview');
editor.addEventListener('input', () => {
const doc = preview.contentDocument;
doc.open();
doc.write(editor.value);
doc.close();
});
</script>
More sophisticated editors debounce the updates (e.g., 300ms delay) to avoid performance issues while typing. They also inject error listeners inside the iframe to catch JavaScript errors and display them in the editor panel.
Sandboxed iframe Security
Running arbitrary user HTML requires isolation. The sandbox attribute on the iframe restricts what the embedded code can do:
<iframe sandbox="allow-scripts allow-same-origin"
srcdoc="..."></iframe>
Common sandbox flags: allow-scripts enables JavaScript execution, allow-same-origin allows access to parent origin storage, and allow-forms enables form submission. Without sandbox, user code could access cookies, localStorage, or navigate the parent page.
Tip: For maximum security, use sandbox="allow-scripts" without allow-same-origin. This prevents the preview from accessing the parent page's storage and APIs.
HTML/CSS/JS Prototyping
Live editors are ideal for rapid prototyping. Instead of creating files, setting up a server, and refreshing, you see changes instantly. This is useful for testing:
- CSS layout experiments (flexbox, grid, animations)
- HTML structure and semantic elements
- Small JavaScript snippets and DOM manipulation
- CSS custom properties and media queries
<div class="card">
<h2>Hello World</h2>
<p>This renders instantly in the preview.</p>
</div>
<style>
.card {
padding: 2rem;
border-radius: 8px;
background: #1a1a2e;
color: #e0e0e0;
font-family: system-ui;
}
</style>
Debugging with Live Preview
When something breaks in your markup, the live preview shows it immediately — no need to reload. Common issues caught instantly:
- Unclosed tags or malformed HTML
- CSS specificity conflicts
- JavaScript runtime errors (displayed in console panel)
- Responsive layout breaks at different viewport sizes
Test your HTML, CSS, and JavaScript in real-time?
Use the HTML Preview tool