Skip to main content
HighClient-sideOWASP A03:2021CWE-79

How to fix: DOM XSS via location.hash Assignment

The page reads from location.hash and assigns it to innerHTML or document.write without sanitization. location.hash is attacker-controlled (the # part of the URL) and enables XSS without any server-side injection.

Why it matters

DOM-based XSS via location.hash requires no server vulnerability. An attacker sends a crafted URL (target.com/page#<img src=x onerror=alert(1)>) and the JavaScript assigns it directly to innerHTML, executing the payload in the victim's browser.

The fragment identifier (#) is never sent to the server. It exists only in the browser. Client-side code that reads window.location.hash or document.location.hash and renders it without sanitization is a DOM XSS sink.

How to fix it

  1. 1Never assign location.hash, location.search, or location.href directly to innerHTML.
  2. 2Use textContent for plain text display of URL-derived values.
  3. 3Sanitize with DOMPurify before innerHTML assignment.
  4. 4Add a CSP to block inline scripts as defense-in-depth.

Code examples

Safe URL fragment handling

JavaScript
// Bad
document.getElementById('content').innerHTML = location.hash.slice(1);

// Good: use textContent for plain text
document.getElementById('content').textContent = decodeURIComponent(location.hash.slice(1));

// Or sanitize with DOMPurify if HTML is needed
import DOMPurify from 'dompurify';
document.getElementById('content').innerHTML = DOMPurify.sanitize(location.hash.slice(1));

References

Detected automatically by VulnRadar. The check id is dom-xss-location-hash, stable across every scan so you can filter or diff on it.

See every client-side check

Questions

How severe is DOM XSS via location.hash Assignment?
VulnRadar rates this high severity in the client-side category. The severity is fixed per check, not scored per site, so the same finding is the same severity on every scan.
Does VulnRadar check for this automatically?
Yes. It runs as part of every scan under the check id dom-xss-location-hash, which stays the same between runs so you can filter, diff, or gate CI on it.
Which standards does DOM XSS via location.hash Assignment map to?
It maps to CWE-79. In the OWASP Top 10 it falls under A03:2021.

Missing a check?

The detection set is open. If you know a misconfiguration this does not catch, propose it: the issue template asks for the threat model, how to detect it, the false-positive risk, and a test fixture, which is the same thing a maintainer would have to work out anyway.

Propose a checkHow a check is built

Scan your own site for dom xss via location.hash assignment

VulnRadar runs this check and hundreds more against a URL in seconds. No agent to install, just paste a URL.

Or scan this site as a demoRead the docs

How to fix: DOM XSS via location.hash Assignment | VulnRadar