DEV BOX

'26/11/18 UPDATE

WEB / SECURITY / FIELD NOTES

I escaped the HTML. Why does clicking the link still run a script?

HTML escaping covers only the HTML parser step. On Chromium 152 the same esc() goes into href, onclick and script, then a new URL allow list, data attributes and JSON handling are tested with the same inputs, along with how a sanitiser can erase plain text.

It is easy to think XSS is dealt with once every template value is escaped. But put a user's link into href and, even after escaping, one click can run a script. HTML escaping covers the HTML parser step and not the URL and JavaScript steps that come after it. After reading this you can look at where a value lands and choose the handling for it, and avoid ruining stored text by running a sanitiser on it.

The examples were run on 2026-11-01 on macOS 27.0.1. The browser is the built-in browser of the Claude desktop app (Chromium 152.0.7977.167) and the server is localhost:4621, written with Node.js v24.21.0. The packages are DOMPurify 3.4.17, EJS 7.0.2 and React DOM 19.2.9. The only code the inputs try to run is hit(label), which just writes one HIT line to the server log. Google Chrome, Safari, Firefox, a real stored XSS path and other template engines were not run. The src cases, the script value outside quotes, CSP with inline script and the screen for double escaping were run separately the same day in the Aside browser (Chromium 154.0.8037.100).

The same function, different results

Every case that escapes uses this one function, the common form that replaces five characters.

const esc = s => String(s)
  .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
  .replace(/"/g, '&quot;').replace(/'/g, '&#39;');

Each case got an input aimed at its own context. The page was opened, and any control that needed pressing was clicked. The inputs differ by context; only the function is the same. The logs in the images show selected lines, folded at 45 columns for phones, and the # lines are added explanations.

Server log. Between tags and a quoted value attribute: no HIT. href with javascript:hit(&#39;href&#39;): HIT href. onclick after an unquoted title: HIT unquoted. String inside onclick: HIT handler. esc() inside script: entities stay in the value, no HIT. JSON.stringify() inside script: HIT script.
All through the same esc(), the red HIT lines appear for href, the unquoted attribute and onclick. The last case, JSON.stringify() alone inside script, also ran.

The green lines are where escaping did its job. < became &lt; so no tag appeared, and " became &quot; so nothing left the attribute value.

Why the red lines? In the href line, the HTML is correctly escaped. But the input javascript:hit('href') needs no character that breaks HTML. The browser turns &#39; in an attribute value back into ', reads the result as a URL, and, as MDN explains, a javascript: navigation target runs as a script. onclick goes in the same order. OWASP notes that for event attributes the HTML parser decodes character references first, so HTML encoding alone does not protect the JavaScript. The unquoted attribute is different again. The escaping function does not touch spaces, so onclick= after the space became a new attribute.

Inside a script tag the result is the opposite. With the value inside a quoted string, as here, esc() stopped this input from running, but the value stayed garbled with entity characters, because character references are not decoded inside a script tag. Outside quotes, an input with nothing for esc() to change, such as hit(`x`), runs as it is. Using JSON.stringify() alone instead, the </script> in the value closed the tag and the code ran as soon as the page opened.

Set out by context, the result looks like this.

Five cards. Between tags and quoted plain attributes like title or value: HTML escaping. Link attributes such as href: parse, check the scheme against an allow list, then escape. Event attributes such as onclick: no value there, use a data attribute and a listener. Inside a script tag: write JSON and turn < into \u003c. When the HTML must stay: a sanitiser, not for URL strings or plain text.
The result above, set out as handling per context. The three red cards are the contexts esc() alone does not cover.

A check on the start of the string does not stop links

The first fix that comes to mind is to see whether the value starts with javascript:. One page held six inputs, and each link was clicked under both checks.

const naiveHref = value => (String(value).startsWith('javascript:') ? '#' : value);

function safeHref(value, base = `http://localhost:${PORT}/`) {
  try {
    const url = new URL(value, base);
    return ['http:', 'https:', 'mailto:'].includes(url.protocol) ? url.href : '#';
  } catch {
    return '#';
  }
}
Server log. The naive check turns only plain into # and leaves upper, space, tab, newline and ctrl as they are, giving five HIT lines. The allow check turns all six into #, with no HIT. https stays, /notes/1 becomes http://localhost:4621/notes/1 and //example.com/a becomes http://example.com/a.
The check that looks only at the start of the string missed five inputs written with mixed case, a space, a tab, a newline and a control character, giving five HIT lines. new URL with an allow list turned the same six inputs into #.

The start-of-string check missed five. Before parsing, the URL Standard removes leading and trailing control characters and spaces and removes tabs and newlines in the middle, and it reads the scheme in lowercase. Since those are the browser's rules, it makes sense to parse with the same rules and look at the resulting protocol. An allow list rather than a block list also filters data: and schemes that appear later. data:, vbscript:, blob: and file: were not clicked, though; only the function's # result was checked in Node.

This function only goes as far as the scheme. As the last line of the log shows, //example.com/a passes. It is not a script, but it is a link to another site. To limit where links can go, add a separate host check. That host check was not run. This function is for links. In a script or iframe src, an http: or https: address passes straight through and loads code from another server.

The default base is this lab's address, so set it to your real site. The input can still turn into another address. With a real base, example.com/a became a path on the site, an empty string became the home page address, and /\evil.example/a became https://evil.example/a (run in Node).

The other fixes, clicked again with the same inputs

The unquoted attribute got quotes. For onclick, the value moved to data-value and a listener in a separate file reads it. Inside script, the value is written as JSON and then < is replaced.

JSON.stringify(v).replace(/</g, '\\u003c')
Server log. href is #. The quoted title keeps onclick inside its value. The data attribute way delivers the whole input as track value. The JSON fix delivers the input in result json-fixed who. Pages with CSP added log CSP blocked inline, directives script-src-elem and script-src-attr.
The four fixes clicked again with the same inputs. No HIT: href became # and in the rest the value stayed as plain characters. The last two lines add only CSP to the unfixed pages, and they log a block report instead of a HIT.

There was no HIT in any of the four. href became #, and in the other three the value stayed as plain characters. The last two lines are a different experiment. Adding only a script-src 'self' header to the unfixed pages produced a block report instead of a HIT on click. MDN describes CSP as a backup for when other defences fail. Those two lines mean execution was blocked, not that the input was fixed. The same header also blocks inline scripts, so the JSON fix then needs a nonce or a separate file.

A sanitiser is a tool for HTML

Escaping shows even the formatting as characters. A sanitiser is what you use when bold text has to survive, and MDN and OWASP advise using a library such as DOMPurify rather than writing your own. OWASP adds that the library must be patched regularly and that changing content after sanitising can undo the protection. The log below also checks whether a template engine's automatic escaping solves the link problem for you.

Output. ejs gives href="javascript:hit(&#39;href&#39;)". react replaces it with throw new Error. DOMPurify rich out is <b>bold</b><img src="x"><a>more</a>. text in if a<b and c>d then stop becomes text out if a<b>d then stop</b>. link out equals the input, and HIT purify-url. Escaping twice gives R&amp;amp;D.
EJS leaves the href alone and React DOM's server-rendered output blocks it. DOMPurify keeps markup and removes script, but it lost the words and c from plain text and returned the URL string unchanged, which gave a HIT on click.

EJS's <%= %> left the href alone, like esc() above. React DOM 19.2.9's server-rendered output (renderToStaticMarkup) replaced the javascript: URL with code that throws an error. Even so, OWASP says this block does not replace URL validation in the application. Client rendering, other versions and other engines were not checked, so print the same output from the engine you use.

DOMPurify removed onerror and the javascript: link from the formatted input and kept <b>. But there are two jobs it should not be given. The URL string javascript:hit('purify-url') has no HTML tag, so it came back unchanged, and putting it in href ran it on click. The plain text if a<b and c>d then stop had <b and c> read as a tag and became if a<b>d then stop</b>. The words and c are gone. The browser's built-in setHTML() gave the same result for this text. According to MDN (updated 2026-10-12) this method does not yet work in some major browsers.

So the order of repair matters. Do not run a sanitiser or escaping in bulk over data you have already stored. A sanitiser can remove the content of plain text for good, and escaping on output a value that was escaped on save makes the source R&amp;amp;D, as in the log, so the screen shows R&amp;D. It is safer to keep the original and handle it where it is written out. If stored data really must change, make a copy first and compare the rows that change. That bulk procedure was not run.

In code review, look at where a value arrives rather than at the function's name. Unless it is between tags or in a quoted ordinary text attribute such as title or value, escaping does not finish the job. The href and onclick here were quoted too. OWASP also says attributes holding URLs, CSS, HTML or JavaScript need handling for those contexts. You can start by finding variables inside href, on* and script, and clicking once with the inputs above. These inputs do not test src, so do not take that value from users, or limit it by host.

THE END
RSS feedBack to the library
COMMENTS BOX

Add your perspective.

Share a question, another approach, or something you have tried.

Newest first

Checking sign-in…

Loading comments…