I Found an Interesting DOM-Based XSS Issue in Contact Form
A contact form's JavaScript used innerHTML to strip HTML tags from the message field, so the browser still parsed attacker-supplied markup and event handlers. The site's Content Security Policy blocked the inline script from running in the tested environment, and the issue was classed as self DOM-based XSS requiring the victim to paste and submit the payload themselves.
medium.com
Published on medium.com
Cybersecurity
The full write-up lives on its author's site
It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.
Context
The target was a website with a contact form, reachable at the fragment route below. The form was displayed automatically whenever the string contact/ appeared in the URL fragment, so the page itself did not need a separate server-side route to show it.
https://www.example.com/#contact/
The feature under review was the Message textarea of that contact form. On submit, a JavaScript function called strip() was meant to remove HTML tags from the message before the form was sent. The write-up is about how that helper, built on innerHTML, introduced a DOM-based XSS sink, and how the site's Content Security Policy (CSP) changed the outcome of the test.

Setup
No accounts, roles, tool versions or special preconditions are described. The testing was done through the contact form itself: open the form, type into the Message textarea, and press the Send Message button. The only environmental variable the report discusses is CSP enforcement: the same behaviour was also tested in a browser environment without CSP enforcement, where the JavaScript executed.
Finding it
What drew attention was not the presence of innerHTML on its own, but the fact that a function written specifically to strip HTML tags used innerHTML to do it. The code involved is:
function strip(html) { var tmp = document.createElement("DIV"); tmp.innerHTML = html; return tmp.textContent || tmp.innerText || "";}
$('form').submit(function() { $('textarea').val(function() { return strip($(this).val()); });});
The intent is clear: take the textarea value, remove any HTML, and write the cleaned value back into the textarea before submission. The problem is the line tmp.innerHTML = html. Assigning to innerHTML asks the browser to parse the string as HTML markup rather than treat it as plain text. The report notes that the browser may parse the string as HTML and that an element's event handler may become relevant to script execution, depending on the browser and the applicable security policies.
Exploitation
Step 1: open the contact form
Navigate to the fragment route so the contact form is displayed:
https://www.example.com/#contact/
The application shows the form whenever contact/ is present in the URL fragment.
Step 2: submit a payload in the Message textarea
The proof-of-concept payload used in the report was:
<img src=x onerror=alert(1) />
This was entered into the Message field, and the Send Message button was clicked. The payload tests whether the browser processes the element and runs its event handler when the image fails to load: src=x resolves to a relative URL that does not exist, so the load fails and onerror becomes relevant.
Step 3: read the developer console
After submission, the browser's developer console showed two errors.
- The browser attempted to request
https://www.example.com/x, which returned a 404 because the image source pointed to a nonexistent resource. The request returned a 404 because the image source pointed to a nonexistent resource. - The browser reported a Content Security Policy violation. The browser had attempted to process the event handler, but the site's CSP blocked the inline JavaScript from executing.
So in the tested environment the sink fired, the element was created, but the script did not run. The report notes that the same behaviour was tested in a browser environment without CSP enforcement, where the JavaScript executed.
Root cause
The mistake is the use of innerHTML as the mechanism for stripping tags. The developer wanted plain text out of the input, but innerHTML is an HTML parsing sink: it hands the string to the HTML parser, which builds elements and processes their attributes, including event handler attributes. The subsequent read of textContent returns only text, but the parsing has already happened by then. A sanitiser that parses untrusted input as HTML to remove HTML is doing the dangerous work it was meant to prevent.
The existing defence that mattered here was CSP. It did not stop the DOM operation, but it blocked the inline handler from executing in the tested environment. The report is explicit that the unsafe DOM operation and the successful execution of JavaScript are two separate things: innerHTML created the unsafe processing behaviour, and CSP reduced the possibility of turning that behaviour into an executable XSS attack in the tested environment. CSP is described as an additional layer of protection, not a substitute for correct input handling.
The report classifies the issue as self DOM-based XSS. Unlike reflected or stored XSS, an attacker could not simply send a link and expect execution. The victim would have to open the contact form, paste a crafted payload into the Message field, and submit it. That social-engineering requirement, together with CSP, significantly reduced the practical impact.
A second observation in the report concerns client-side sanitisation in general. Because strip() runs in the user's browser, its behaviour can be changed by the user. An intercepting proxy can inspect and modify HTTP requests during authorised testing, so even if the browser removes HTML before sending, the submitted request can be modified independently of that JavaScript processing. Client-side sanitisation therefore cannot be the only control; validation and sanitisation must also be enforced on the server.
Impact
In the tested environment, the impact was limited. The browser parsed the injected markup and tried to load the image, but CSP blocked the inline handler, so no script executed. The report also states that the same behaviour was tested in a browser environment without CSP enforcement, where the JavaScript executed.
Exploitation against a real visitor would require the attacker to convince the victim to open the contact form, paste the crafted payload into the Message field, and submit it. The report does not claim any impact beyond that: the practical impact was significantly reduced by the required interaction and by CSP, and identifying unsafe JavaScript behaviour does not automatically mean the issue is exploitable against every visitor. Actual impact depends on execution conditions, browser protections and the user interaction required.
Fix
The report gives four recommendations rather than describing a change that was made.
- Avoid
innerHTMLwith untrusted input. If the application expects plain text, handle it as plain text. The report's example usestextContent, which treats the value as text instead of interpreting it as HTML:
function displayMessage(userInput) { var element = document.createElement("div"); element.textContent = userInput; return element;}
-
Validate on the server. Client-side validation is useful for user experience but should never be the only security mechanism; the server should independently validate and sanitise incoming data according to the application's requirements.
-
Use a trusted HTML sanitisation library. If an application genuinely needs to accept HTML, use a well-maintained library such as DOMPurify rather than custom JavaScript or regular expressions.
-
Maintain a strong Content Security Policy. A properly configured CSP reduces the impact of certain XSS vulnerabilities, but it is defence in depth, not the primary solution.
Variants to test
- Other DOM sinks fed by the same helper. Look for functions that parse input with
innerHTML,outerHTML,insertAdjacentHTMLordocument.writeand then read back text. A positive result is the browser issuing a request for a resource (as withsrc=xproducing a request to/x) or a CSP violation, which shows the markup was parsed. - Event handlers other than
onerror. Try handlers that fire without a network round trip, such asonfocuswith autofocus, oronloadon elements that load immediately. A positive result is a CSP violation or execution in a browser without CSP, showing the handler attribute survived parsing. - CSP gaps. Check whether the policy allows
unsafe-inline, whether it covers only some directives, and whether JSONP endpoints or allowed script hosts can be abused. A positive result is the same payload executing under the site's real policy. - Client-side sanitisation bypass. Submit the form through an intercepting proxy and replace the sanitised message with the raw payload. A positive result is the server accepting the unsanitised value, which shows the server does not re-validate.
- Fragment-driven routing. Since the form appeared whenever
contact/was in the fragment, test other fragment values that the application may act on. A positive result is a fragment value that reaches a DOM sink without user interaction.
What happened, in plain words
A security researcher was looking at a website that has a contact form, the kind of page where you type your name, your email address and a message, then press a button to send it. The form had a small piece of JavaScript (the programming language that runs inside your browser) whose job was to clean up whatever you typed in the Message box before sending it, by removing any HTML tags. HTML tags are the instructions in angle brackets, like <b> for bold, that tell a browser how to display something.
The cleaning function was written in a way that looks sensible but is actually risky. To remove the tags, it asked the browser to read your message as if it were a web page, and only then took the plain text back out. That moment of reading it as a web page is the problem: the browser can act on what it finds there, including instructions that run code. This kind of flaw is called DOM-based Cross-Site Scripting, or DOM-based XSS. The DOM is the browser's internal model of the page, and XSS means getting your own code to run inside someone else's website.
What makes this case interesting is that the website had a Content Security Policy, or CSP. A CSP is a set of rules the site sends to your browser saying which scripts are allowed to run. When the researcher tried a test payload, the browser did start processing it, but the CSP stopped the code from actually executing. The report also notes that in a browser without that policy, the code did run.

The image at the top of the article is described in the report as AI generated.
1. The page and the feature
The target was a website with a contact form, reachable at this address:
https://www.example.com/#contact/
Let us unpack that address. The part before the # is the normal page address. Everything after the # is called the URL fragment, sometimes called the hash. In a normal web page the fragment just scrolls you to a section, but modern sites often use it as a kind of mini-address: JavaScript reads it and decides what to show. Here, the site displayed the contact form automatically whenever the text contact/ appeared in the fragment. That means the page did not need a separate server-side address for the form; the browser did the work of showing it.
The feature under review was the Message textarea, the large box where you type your message. When you press the submit button, a JavaScript function called strip() was supposed to remove HTML tags from your message before the form was sent to the server. The server is the computer that stores the site and receives the form. The write-up is about how that helper function, built on a browser feature called innerHTML, created a place where injected markup gets processed, and how the site's CSP changed the outcome of the test.
2. Setting up
The report does not describe any accounts, user roles, tool versions or special preconditions. The testing was done through the contact form itself: open the form, type into the Message textarea, and press the Send Message button. The only environmental difference the report discusses is whether CSP is enforced. The same behaviour was also tested in a browser environment without CSP enforcement, where the JavaScript executed.
3. Finding it
What drew attention was not the presence of innerHTML on its own, but the fact that a function written specifically to strip HTML tags used innerHTML to do it. The code involved is:
function strip(html) { var tmp = document.createElement("DIV"); tmp.innerHTML = html; return tmp.textContent || tmp.innerText || "";}
Line by line, in plain words:
function strip(html) {starts a reusable block of code namedstrip, which takes one input, here calledhtml(the text you typed).var tmp = document.createElement("DIV");creates a brand new, emptydivelement in the browser's memory. Adivis a generic container on a web page. It is not placed on the visible page; it exists only inside the browser's model of the page, the DOM.tmp.innerHTML = html;is the important line. It takes your text and asks the browser to interpret it as HTML, filling the invisibledivwith whatever elements your text describes. This is the moment the browser parses your input as markup.return tmp.textContent || tmp.innerText || "";reads the plain text back out of thatdiv.textContentgives the text without tags;innerTextis an older alternative; the||means "use the first one that exists", and""is a fallback empty string. So the function hands back what looks like plain text.- The closing
}ends the function.
The second piece of code is what calls it:
$('form').submit(function() { $('textarea').val(function() { return strip($(this).val()); });});
$('form').submit(function() {uses jQuery, a popular JavaScript library, to say: when the form is submitted, run this function first. The$is jQuery's shorthand for "find this element".$('textarea').val(function() {finds the textarea and sets its value using a function, so the new value is calculated at that moment.return strip($(this).val());takes the current text in the textarea, passes it tostrip(), and returns the cleaned result.- The closing
});});closes the inner function and the outer submit handler.
The intent is clear: take the textarea value, remove any HTML, and write the cleaned value back into the textarea before submission. The problem is the line tmp.innerHTML = html. Assigning to innerHTML asks the browser to parse the string as HTML markup rather than treat it as plain text. The report notes that the browser may parse the string as HTML and that an element's event handler may become relevant to script execution, depending on the browser and the applicable security policies. Think of it like a translator who reads your note aloud in a foreign language to understand it, and in doing so accidentally follows any instructions written on it.
4. Trying it out
Step 1: open the contact form
Navigate to the fragment route so the contact form is displayed:
https://www.example.com/#contact/
The application shows the form whenever contact/ is present in the URL fragment. This step is just to get the form on screen; there is nothing secret about it.
Step 2: submit a payload in the Message textarea
The proof-of-concept payload used in the report was:
<img src=x onerror=alert(1) />
This was entered into the Message field, and the Send Message button was clicked. A payload is simply the input you use to test a theory. This one is an image tag. src=x tells the browser to load an image from a relative address called x, which does not exist. onerror=alert(1) is an event handler: an instruction that says "if loading the image fails, run this code". alert(1) is the classic harmless test that makes a pop-up box appear with the number 1. The payload tests whether the browser processes the element and runs its event handler when the image fails to load.
Step 3: read the developer console
After submission, the browser's developer console showed two errors. The developer console is a panel built into every browser, usually opened with F12, where the browser reports problems and where developers inspect what is happening.
- The browser attempted to request
https://www.example.com/x, which returned a 404 because the image source pointed to a nonexistent resource. A 404 is the standard "not found" answer from a web server. The request returned a 404 because the image source pointed to a nonexistent resource. - The browser reported a Content Security Policy violation. The browser had attempted to process the event handler, but the site's CSP blocked the inline JavaScript from executing. Inline JavaScript means code written directly inside the page or inside an attribute, rather than loaded from a separate file.
So in the tested environment the sink fired, the element was created, but the script did not run. A sink is the place in the code where untrusted data finally gets used in a way that can be dangerous. The report notes that the same behaviour was tested in a browser environment without CSP enforcement, where the JavaScript executed.
5. Why it happened
The mistake is the use of innerHTML as the mechanism for stripping tags. The developer wanted plain text out of the input, but innerHTML is an HTML parsing sink: it hands the string to the HTML parser, which builds elements and processes their attributes, including event handler attributes. The subsequent read of textContent returns only text, but the parsing has already happened by then. A sanitiser that parses untrusted input as HTML to remove HTML is doing the dangerous work it was meant to prevent. It is like checking a parcel for dangerous contents by opening it and setting everything inside in motion.
The existing defence that mattered here was CSP. It did not stop the DOM operation, but it blocked the inline handler from executing in the tested environment. The report is explicit that the unsafe DOM operation and the successful execution of JavaScript are two separate things: innerHTML created the unsafe processing behaviour, and CSP reduced the possibility of turning that behaviour into an executable XSS attack in the tested environment. CSP is described as an additional layer of protection, not a substitute for correct input handling.
The report classifies the issue as self DOM-based XSS. Unlike reflected or stored XSS, an attacker could not simply send a link and expect execution. Reflected XSS bounces your input straight back from the server; stored XSS saves it and shows it to other people later. Here, the victim would have to open the contact form, paste a crafted payload into the Message field, and submit it. That social-engineering requirement, together with CSP, significantly reduced the practical impact. Social engineering means tricking a person into doing something, rather than breaking in technically.
A second observation in the report concerns client-side sanitisation in general. Because strip() runs in the user's browser, its behaviour can be changed by the user. An intercepting proxy can inspect and modify HTTP requests during authorised testing, so even if the browser removes HTML before sending, the submitted request can be modified independently of that JavaScript processing. A proxy is a program that sits between your browser and the server and lets you read and edit the traffic. Client-side sanitisation therefore cannot be the only control; validation and sanitisation must also be enforced on the server.
6. What the impact was
In the tested environment, the impact was limited. The browser parsed the injected markup and tried to load the image, but CSP blocked the inline handler, so no script executed. The report also states that the same behaviour was tested in a browser environment without CSP enforcement, where the JavaScript executed.
Exploitation against a real visitor would require the attacker to convince the victim to open the contact form, paste the crafted payload into the Message field, and submit it. The report does not claim any impact beyond that: the practical impact was significantly reduced by the required interaction and by CSP, and identifying unsafe JavaScript behaviour does not automatically mean the issue is exploitable against every visitor. Actual impact depends on execution conditions, browser protections and the user interaction required.
7. How to fix it
The report gives four recommendations rather than describing a change that was made.
- Avoid
innerHTMLwith untrusted input. If the application expects plain text, handle it as plain text. The report's example usestextContent, which treats the value as text instead of interpreting it as HTML:
function displayMessage(userInput) { var element = document.createElement("div"); element.textContent = userInput; return element;}
function displayMessage(userInput) {starts a function that takes the user's text.var element = document.createElement("div");creates an emptydivin memory, just like before.element.textContent = userInput;puts the text in as plain text. The browser does not parse it as HTML, so any tags stay as visible characters rather than becoming elements.return element;hands the element back.- The closing
}ends the function.
-
Validate on the server. Client-side validation is useful for user experience but should never be the only security mechanism; the server should independently validate and sanitise incoming data according to the application's requirements. Validation means checking that the data is what you expect, for example that a message is not empty or too long.
-
Use a trusted HTML sanitisation library. If an application genuinely needs to accept HTML, use a well-maintained library such as DOMPurify rather than custom JavaScript or regular expressions. A library is a collection of code written and reviewed by others; DOMPurify is one built specifically to clean HTML safely. Regular expressions are patterns for matching text, and they are notoriously hard to get right for HTML.
-
Maintain a strong Content Security Policy. A properly configured CSP reduces the impact of certain XSS vulnerabilities, but it is defence in depth, not the primary solution. Defence in depth means several layers of protection, so that one failure does not sink you.
8. Other things worth testing
- Other DOM sinks fed by the same helper. Look for functions that parse input with
innerHTML,outerHTML,insertAdjacentHTMLordocument.writeand then read back text. A positive result is the browser issuing a request for a resource (as withsrc=xproducing a request to/x) or a CSP violation, which shows the markup was parsed. - Event handlers other than
onerror. Try handlers that fire without a network round trip, such asonfocuswith autofocus, oronloadon elements that load immediately. A positive result is a CSP violation or execution in a browser without CSP, showing the handler attribute survived parsing. - CSP gaps. Check whether the policy allows
unsafe-inline, whether it covers only some directives, and whether JSONP endpoints or allowed script hosts can be abused. A positive result is the same payload executing under the site's real policy. JSONP is an older technique for loading data as a script. - Client-side sanitisation bypass. Submit the form through an intercepting proxy and replace the sanitised message with the raw payload. A positive result is the server accepting the unsanitised value, which shows the server does not re-validate.
- Fragment-driven routing. Since the form appeared whenever
contact/was in the fragment, test other fragment values that the application may act on. A positive result is a fragment value that reaches a DOM sink without user interaction.
Glossary
- JavaScript: the programming language that runs inside web browsers and makes pages interactive.
- HTML: the markup language that describes the structure of a web page, using tags in angle brackets.
- HTML tag: an instruction such as
<b>or<img>that tells the browser what to create or display. - DOM: the browser's internal tree-like model of the page, which scripts can read and change.
- DOM-based XSS: a cross-site scripting flaw where the dangerous processing happens entirely in the browser, in the page's DOM, rather than on the server.
- XSS (Cross-Site Scripting): a class of vulnerability where an attacker gets their own code to run inside someone else's website, in a victim's browser.
- CSP (Content Security Policy): rules a website sends to the browser saying which scripts and resources are allowed to load and run.
- Inline JavaScript: code written directly inside a page or an HTML attribute, rather than in a separate file.
- innerHTML: a browser property that asks the browser to interpret a string as HTML and build elements from it.
- textContent: a browser property that reads or sets the plain text of an element, without interpreting HTML.
- innerText: an older browser property similar to
textContentthat returns visible text. - Sink: the place in code where untrusted data is finally used in a way that can be dangerous.
- Sanitisation: cleaning input so that dangerous parts are removed or neutralised.
- Validation: checking that input is what the application expects.
- Client-side: happening in the user's browser.
- Server-side: happening on the computer that hosts the website.
- URL fragment (hash): the part of a web address after the
#symbol, which the browser and scripts can read. - Textarea: a large multi-line text input box on a web page.
- Payload: the input used in a test to try to trigger a behaviour.
- Event handler: an attribute such as
onerrororonloadthat tells the browser to run code when something happens. - alert(1): a harmless JavaScript command that shows a pop-up box, commonly used to prove code can run.
- Developer console: a panel in the browser, usually opened with F12, that shows errors and lets developers inspect the page.
- 404: the standard web server answer meaning "not found".
- jQuery: a popular JavaScript library that simplifies finding and changing page elements; its shorthand is
$. - Intercepting proxy: a tool that sits between the browser and the server and lets you read and edit the traffic.
- HTTP request: the message a browser sends to a server to ask for a page or send data.
- Self XSS: an XSS flaw that only triggers if the victim themselves pastes or enters the payload, so it needs social engineering.
- Reflected XSS: XSS where the malicious input is immediately echoed back by the server in its response.
- Stored XSS: XSS where the malicious input is saved by the server and shown to other users later.
- Social engineering: tricking a person into taking an action, rather than attacking technology directly.
- DOMPurify: a well-maintained library for safely cleaning HTML.
- Regular expression: a pattern for matching text, often used for validation but hard to make safe for HTML.
- Defence in depth: using several layers of protection so that one failure does not cause a breach.
- unsafe-inline: a CSP setting that allows inline scripts, weakening the policy.
- JSONP: an older technique for loading data as a script, which can sometimes be abused to bypass CSP.
- Fragment-driven routing: using the URL fragment to decide which part of a page or which form to show.