Escape model output before rendering it
A model can return HTML, by accident or because someone asked for it in the prompt. With innerHTML that HTML runs.
The constant MODEL_OUTPUT is a model answer that includes <img src="" onerror=...>. If you render it as is with innerHTML, the browser creates the image, has nothing to load and runs onerror: in a real app that can read the user's session.
Write escapeHtml(str) that replaces &, <, >, " and ' with &, <, >, " and '. Then render the escaped MODEL_OUTPUT inside #out, so it shows as text.
Challenges 0/4
- Escapes all five characters
- Escapes & first (no double escaping)
- #out shows the tag as text, with no <img> created
- The onerror handler did not run
function escapeHtml(str) {
// replace & first, then < > " '
return str;
}
document.getElementById('out').innerHTML = escapeHtml(MODEL_OUTPUT);
console.log('rendered');Tab indents, Ctrl+Z undoes. To leave the editor with the keyboard: Esc, then Tab.
Why this matters
A model's output is text you do not control. It may contain HTML because the user asked for it, because it came in a retrieved document, or because someone hid it in an email for your assistant to repeat. If you insert it with innerHTML, that HTML runs with the session of whoever is looking at the page. Escaping before you render is the minimum defence in any chat interface, and it does not depend on how clever the model is. The server-side measures are in the security checklist for Ollama.
Go deeper: the OWASP reference →
This in production, with your data? Let's talk for 15 minutes →