Web Platform interview questions: XSS and web security
Reviewed by Mark Dickie · Last updated
5 questions on this page you can answer and see marked on the spot. Go to the first one
Cross-site scripting (XSS) is a class of web security vulnerability where an attacker injects untrusted data into a web page that is then executed in another user's browser. For a Web Platform interview, you should know the three main XSS types (stored, reflected, DOM-based), how context-aware output encoding stops injection, and how a Content Security Policy adds defense in depth.
Expect questions on escaping HTML entities versus JavaScript string contexts, the difference between textContent and innerHTML, cookie flags like HttpOnly and SameSite, and Trusted Types. You may also be asked to read a vulnerable snippet and identify the exact sink that makes it exploitable.
What XSS types should you know for a Web Platform interview?
| Type | Where the payload lives | Typical entry point |
|---|---|---|
| Stored | Server-side database or cache | Comment fields, profile bios |
| Reflected | URL parameter or request body | Search boxes, redirect params |
| DOM-based | Client-side code only, no server round trip | location.hash read into innerHTML |
How do you prevent XSS in modern web applications?
- Encode output for the context it lands in: HTML body, attribute, JavaScript, or URL encoding are not interchangeable.
- Prefer safe DOM APIs such as
textContent,document.createElement, andelement.setAttributeoverinnerHTML. - Set a strict Content Security Policy that disallows inline scripts and restricts script sources to trusted origins.
- Apply
HttpOnlyso session tokens cannot be read by JavaScript, and setSameSiteto mitigate CSRF by restricting cross-site cookie transmission. - Adopt Trusted Types where supported so the browser refuses any sink assignment that is not a policy-sanitized string.
What sinks do interviewers ask you to identify?
Interviewers often hand you a code snippet and ask which line is the XSS sink. Common culprits are innerHTML, outerHTML, document.write, eval, setTimeout with a string argument, and jQuery's .html() wrapper. The fix is almost always to avoid passing untrusted input to the sink, or to sanitize and encode before the assignment.
Key facts
- Tarmac has 11 Web Platform interview questions on this topic, 10 of them on this page, at difficulty 1–5 of 5.
- Tarmac tracked 748 job postings asking for Web Platform in November 2026.
- Roles asking for Web Platform advertise a median base salary of US$187,116, across 152 job postings as of November 2026.
- Tarmac last reviewed these Web Platform interview questions on 3 December 2026.
At a glance
| Questions | 10 shown · 11 in the bank |
|---|---|
| Difficulty | 1–5 of 5 |
| Formats | Multiple choice, Ordering, Code output, True / false, Short answer, Fill in the blank, Multiple answer, Find the bug, Flashcard, Coding exercise |
| Interactive | 1 run your code against tests, in the app |
What you'll review
- xss
Practice questions
Try one before you open the answer. Pick an option and press Check; it's marked on the spot.
In a stored (persistent) cross-site scripting attack, where does the malicious script come from when a victim's browser runs it?#
Options
Show answer
Stored XSS script comes from data the application saved earlier, such as a comment in its database. The application then puts that data into pages it serves to other users without escaping it. Because the payload lives on the server, it runs for every viewer, not just someone who clicked a crafted link. A crafted link that only works for whoever clicks it is reflected XSS.
Stored XSS happens when attacker input, such as a comment or profile field, is saved on the server and later rendered without escaping, so it runs for everyone who views that content. A crafted URL echoed back in a single response is reflected XSS, not stored. A malicious extension is a different threat model and not XSS. A forged cross-site request that rides on the victim's cookies is CSRF.
Put the steps of a classic reflected XSS attack in the order they happen, from first to last.#
Put these in order
Show answer
A reflected XSS attack happens in this order: the attacker builds a link with a script payload in it, the victim clicks it, the server copies the unescaped payload into its HTML response, the victim's browser runs the script under the site's origin, and the script sends the stolen data to the attacker. Each step only works if the step before it has already happened.
Each step depends on the one before it. The attacker first has to build the malicious link. A victim then has to click it so the request reaches the server. The server reflects the payload into the page without escaping it. Only after the browser gets that response can it run the script, and it runs it with the vulnerable site's origin. Once the script is running, it can read data such as non-HttpOnly cookies and send it to the attacker.
This runs in a modern browser. What does it log to the console? Give both lines exactly.#
const el = document.createElement('div');
el.textContent = '<b>hi</b>';
console.log(el.children.length);
console.log(el.innerHTML);Show answer
0
<b>hi</b>
Setting textContent puts in a single text node and never parses markup, so no <b> element is created and el.children.length is 0. That is why textContent is a safe sink for untrusted data and prevents XSS. Reading innerHTML serializes the text node, and the serializer escapes < and > (and &) in text, so it returns <b>hi</b> instead of the raw tag.
True or false: Setting the HttpOnly flag on a session cookie prevents an XSS vulnerability from letting an attacker's injected script perform actions as the logged-in user.#
Options
Show answer
No. An HttpOnly cookie does not stop XSS from acting as the user. The flag only blocks scripts from reading the cookie. Injected code still runs in the victim's origin and can send same-origin requests, and the browser attaches the cookie to them automatically. It can also read the DOM and CSRF tokens. HttpOnly limits the damage by preventing cookie theft, but it does not prevent the attack.
The statement is false. HttpOnly only stops JavaScript from reading the cookie through document.cookie, so the session token can't be stolen and sent off-site. The injected script still runs in the victim's origin, though. It can call fetch or submit forms to same-origin endpoints, and the browser attaches the session cookie to those requests automatically. It can also read the page's DOM, including CSRF tokens, and change what the user sees. HttpOnly limits the damage from XSS, but it does not stop an attacker from acting as the user. The fix is to prevent the injection in the first place, using output encoding and a Content Security Policy.
A server template HTML-escapes a user-supplied value (escaping <, >, &, ", ') and inserts it as <a href="{{userUrl}}">profile</a>. Explain why this can still lead to XSS, and name a concrete mitigation.#
Show answer
HTML escaping prevents breaking out of the attribute, but the value is interpreted as a URL. An attacker can supply javascript:alert(document.cookie), which contains no characters that need escaping, and the script runs when the link is clicked. Output encoding has to match the context. Here, the URL should be parsed and its scheme checked against an allowlist of http: and https:, rejecting anything else. A CSP without 'unsafe-inline' can serve as defense in depth because it blocks javascript: URL execution.
XSS defenses depend on context. Entity-escaping makes a value safe in HTML text and inside quoted attributes. In an href, though, the browser treats the value as a URL, and a javascript: URL runs code when someone navigates to it. The payload javascript:alert(1) contains no characters that HTML escaping changes, so it reaches the page unchanged. The fix is to validate the URL scheme against an allowlist such as http/https, and optionally add a CSP that blocks inline script.
A site sends the header Content-Security-Policy: script-src 'self'. An attacker injects <button onclick="steal()"> into the page. The inline handler does not run, because CSP blocks inline scripts and event handlers unless the policy includes the source keyword _____ (the insecure opt-out). The safer way to allow one specific inline <script> block is to give it a random per-response value in its _____ attribute and list that same value in script-src.#
Show answer
A site sends the header Content-Security-Policy: script-src 'self'. An attacker injects <button onclick="steal()"> into the page. The inline handler does not run, because CSP blocks inline scripts and event handlers unless the policy includes the source keyword **'unsafe-inline'** (the insecure opt-out). The safer way to allow one specific inline <script> block is to give it a random per-response value in its **nonce** attribute and list that same value in script-src.
With CSP Level 2 and later, a script-src directive that leaves out 'unsafe-inline' blocks inline <script> bodies, inline event-handler attributes like onclick, and javascript: URLs. That is why injected markup such as onclick="steal()" does nothing. Adding 'unsafe-inline' turns that protection off for the whole page. A nonce allows only the inline scripts that carry a matching nonce attribute. The server generates a fresh unpredictable value for each response, so an attacker cannot guess it and add it to injected script tags. A hash source ('sha256-...') also works, but it goes in the policy rather than in an attribute, so the attribute here must be nonce. Also, inline event handlers stay blocked even when a nonce is used.
Which of these meaningfully reduce the risk of cross-site scripting (XSS)?#
Options
Pick every one that applies.
Show answer
Three of these help: rendering user input as text via textContent, context-aware output encoding, and a Content-Security-Policy that restricts which scripts run all cut off injection or execution. Storing the session token in localStorage does the opposite — it makes the token readable by any injected script, worsening XSS impact rather than reducing it.
XSS is injecting attacker-controlled script into a page. Treating input as text (textContent), escaping output for its context, and a strict CSP all cut off injection or execution. Moving the token to localStorage does the opposite — it makes the token readable by any injected script, so it worsens XSS impact.
This renders a username from the URL into the page. What is the security flaw?#
const name = new URLSearchParams(location.search).get('name');
document.getElementById('greeting').innerHTML = 'Hello, ' + name;Options
Show answer
Assigning untrusted input to innerHTML lets an attacker inject HTML/script (XSS)
name is attacker-controllable via the URL, and writing it into innerHTML parses it as HTML — a payload like <img src=x onerror=alert(1)> executes. This is a DOM-based XSS sink. Use textContent (which never parses HTML) for untrusted text, or sanitize before any HTML insertion.
What is mutation XSS (mXSS)? Why can a sanitizer that serializes its cleaned DOM back to a string (for example el.innerHTML = sanitize(input)) still be bypassed, and how do the browser's Sanitizer API / Element.setHTML() address that gap? Note any browser availability caveats.#
Show answer
mXSS is XSS where input that looks inert is changed by the HTML parser or serializer into markup that executes script, often after a sanitizer has already accepted it. A string-based sanitizer parses the input, cleans the DOM, serializes it to a string, and the page parses that string again with innerHTML. HTML serialization and re-parsing do not round-trip exactly: the second parse can build a different tree. Foreign content (<svg>, <math>) switches namespaces and changes how tags and attributes are interpreted, and elements such as <noscript>, <style>, <template> and <form> change parser behavior. Parser error recovery can also move nodes. Text that was harmless in the first parse can therefore become an element with an event handler (for example <img onerror>) in the second. Published DOMPurify bypasses exploited this kind of namespace and context confusion. The Sanitizer API's Element.setHTML() reduces the problem: it parses the string in the context of the target element, sanitizes the resulting fragment, and inserts it, so there is no serialize-and-reparse step. The sanitizer does not depend on a separate parse in a different context. Caveats: setHTML() and the Sanitizer API are not universally available. They ship only in some recent browser versions and the spec has changed over time, so check MDN or caniuse for the target versions and keep a fallback. DOMPurify with RETURN_DOM or RETURN_DOM_FRAGMENT avoids the string round-trip and inserts returned nodes directly, but DOMPurify presents this as a mitigation, not a complete fix, because its nodes are still produced in a different parsing context than the real target. Pair any sanitizer with Trusted Types (enforced via a Content-Security-Policy require-trusted-types-for 'script' directive) so raw innerHTML assignments are rejected unless they go through a policy. Trusted Types enforces the sink but does not sanitize by itself.
This is a senior-level question about mXSS. The core mechanism is that HTML serialization followed by re-parsing does not round-trip: the string a sanitizer produces can be parsed into a different tree than the one it cleaned. Foreign content, raw-text and template elements, and error recovery are the usual triggers, and DOMPurify bypasses exploited namespace confusion of this kind. The fix the card describes is to avoid the second parse: Element.setHTML() parses the input in the target element's context, sanitizes that fragment, and inserts it in one step. The card also notes that this API is not universally available and has changed in the spec, and that DOMPurify's RETURN_DOM mode is a mitigation rather than a guaranteed fix because its nodes come from a different parsing context. Trusted Types complements either approach by blocking unsanitized string sinks.
A server-side template puts untrusted data inside an inline script, like this: <script>var data = OUTPUT;</script>. JSON.stringify alone is not safe here. The HTML tokenizer ends the script at </script> before any JavaScript runs, and it also treats <!-- and <script specially. Older engines also treat U+2028 and U+2029 as line terminators.#
Starter code
function toScriptStringLiteral(s) {
// TODO: JSON.stringify is not enough inside <script>
return JSON.stringify(s);
}Your solution must pass
- script breakout
- quote, backslash, newline
This one is written and run, not read. Solve it in the app and your code is executed against these tests and the hidden ones.
Sources
The official documentation these questions are checked against:
Related interview questions
Job market
See web-platform salaries and hiring demand from live job postings.
The other 1 question
This page shows 10 and marks what you pick. That's as far as a page can go. A free account opens the other 1 and keeps every answer. What you miss comes back until it's right: after a day, then at longer gaps.
Free · the whole bank · 100 answers per 30 days, each marked with written feedback