Data and text · Easy · 10 min

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=x onerror=...>. If you render it as is with innerHTML, the browser creates the image, the load fails and onerror runs: in a real app that can read the user's session.

Write escapeHtml(str) that replaces &, <, >, " and ' with &amp;, &lt;, &gt;, &quot; and &#39;. 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');
Console output appears here (console.log).

Go deeper: the OWASP reference →

This in production, with your data? Let's talk for 15 minutes →