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
- 1Never assign location.hash, location.search, or location.href directly to innerHTML.
- 2Use textContent for plain text display of URL-derived values.
- 3Sanitize with DOMPurify before innerHTML assignment.
- 4Add a CSP to block inline scripts as defense-in-depth.
Code examples
Safe URL fragment handling
// 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.
More client-side checks
- HighCSP Allows 'unsafe-inline' Scripts
- MediumCSP Allows 'unsafe-eval'
- HighpostMessage Without Origin Validation
- HighSensitive Data Stored in localStorage
- Highdocument.write() in Page Scripts
- Higheval() in Client-Side JavaScript
- MediumExternal Script Without Subresource Integrity
- MediumJavaScript Source Map Exposed in Production
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.