HTML entities and script injection
Escaping text before displaying it is the first defence against script injection. Here is what to escape, and where.
Why text must be escaped
When a page displays text that comes from elsewhere, a comment, a username, a search term, a database field, the browser cannot tell that text apart from the code around it: it reads everything as HTML. If the name entered is the following, the page inserts an image whose failure to load runs a script:
<img src=x onerror="alert(document.cookie)">
This is script injection, or XSS (cross-site scripting). The attacker's code runs in the page with
the visitor's rights: it reads what the page displays, sends requests on the visitor's behalf, and reads cookies
not marked HttpOnly.
Escaping means replacing the characters that carry meaning in HTML with entities, which the browser displays instead of interpreting. The same name becomes:
<img src=x onerror="alert(document.cookie)">
The visitor sees the text exactly as entered, and nothing runs.
The five characters, by context
| Character | Entity | Role in HTML |
|---|---|---|
& | & | Starts an entity. |
< | < | Opens a tag. |
> | > | Closes a tag; escaping it is customary. |
" | " | Closes a double-quoted attribute. |
' | ' | Closes a single-quoted attribute. |
Between two tags, & and < are the decisive characters. In an attribute value, they
are & and the quotation mark that delimits it. Escaping all five everywhere is the simplest rule,
and it is what the minimal mode of the kit's HTML entity encoder does.
This rule assumes quoted attributes. Without quotes, a single space ends the value:
<div title=VALUE> with the value x onmouseover=alert(1) adds an event attribute
without using any of the five characters. Attributes are therefore always written in quotes.
Where HTML escaping is not enough
Entities protect text that the browser reads as HTML. In other contexts, another language takes over, with its own rules:
- Inside a
<script>block: the browser does not decode entities there, and the text is JavaScript. A quote, a backslash or a line break breaks a string, and</script>closes the block. Pass data through an escapeddata-*attribute instead, or through a<script type="application/json">block whose<are written\u003c, read back withJSON.parse. - In an event attribute (
onclick,onerror…): the browser decodes the entities, then runs the result as JavaScript. A'turns back into an apostrophe before execution. Attach handlers withaddEventListenerand keep data out of code. - In an address (
href,src):javascript:alert(1)contains no character to escape. Check the scheme, accepting onlyhttps:,http:ormailto:, and encode values as explained in URL encoding explained. - In CSS (
styleattribute,<style>block): a value can load an external resource withurl(…)or break out of its declaration. Only use values picked from a fixed list there.
Let the template engine escape
Most template engines escape what they output automatically. The safe path is the default; the risk lies in the syntax that turns escaping off:
| Engine | Escaped | Unescaped |
|---|---|---|
| Razor (ASP.NET Core) | @value | @Html.Raw(value) |
| React | {value} | dangerouslySetInnerHTML |
| Vue | {{ value }} | v-html |
| Twig | {{ value }} | {{ value|raw }} |
| Jinja2 (Flask) | {{ value }} | {{ value|safe }} |
| DOM | textContent | innerHTML |
Flask turns escaping on for .html templates; Jinja2 used on its own leaves it off until configured.
ASP.NET Core's default encoder also writes non-ASCII characters as numeric references (é becomes
é), like the second mode of the kit's encoder.
Two rules complete the table. Keep unescaped output for HTML you produce yourself or have sanitised. And escape on
output, not on input: text stored already escaped gets escaped a second time by the engine, and the visitor sees
& instead of &.
A CSP as a second line of defence
The Content-Security-Policy header tells the browser which scripts it may run. A policy without
'unsafe-inline' blocks scripts written in the page and event attributes: an injection that slipped
through runs nothing.
Content-Security-Policy: default-src 'self'; script-src 'self'; object-src 'none'; base-uri 'none'
Inline scripts the site needs are allowed with a nonce or a hash. A CSP complements escaping: it limits the damage
of an oversight. The kit's pages apply one, which among other things forbids them any network request
(connect-src 'none').
Encoding is not sanitising
Escaping turns all HTML into text. When you must accept rich HTML, from a WYSIWYG editor, formatted comments or
imported content, escaping would display the tags instead of applying them. You then need a
sanitiser: it parses the HTML, keeps the allowed tags and attributes (p,
strong, a with an https: address…) and removes the rest, scripts,
on* attributes and javascript: addresses included.
Leave this job to a proven library: DOMPurify in the browser and in Node.js, HtmlSanitizer in .NET, the OWASP Java HTML Sanitizer in Java, nh3 in Python. They parse HTML the way a browser does, where a regular expression lets through the variants a browser accepts. Sanitised HTML is then output unescaped, preferably under a CSP.
Sharing decoded text
A password stored in an XML file or an email template sometimes appears as entities. Once decoded, “Send with onlyU” passes it to onlyU from one tab to another in your browser, without putting it in an address or routing it through the kit's server. onlyU encrypts it in your browser and creates a link your recipient opens only once, valid for 24 hours, after which the link disappears. It is free, with no sign-up.