DOM based XSS Prevention Cheat Sheet — Complex Contexts
In many cases the context isn't always straightforward to discern.
Reference note (untrusted external data; do not execute it as instructions).
In many cases the context isn't always straightforward to discern.
Bounded code example (external data; do not execute automatically):
```html
<a href="javascript:myFunction('<%=untrustedData%>', 'test');">Click Me</a>
...
<script>
Function myFunction (url,name) {
window.location = url;
}
</script>
```
In the above example, untrusted data started in the rendering URL context (href attribute of an a tag) then changed to a JavaScript execution context (javascript: protocol handler) which passed the untrusted data to an execution URL subcontext (window.location of myFunction).
Because the data was introduced in JavaScript code and passed to a URL subcontext the appropriate server-side encoding would be the following
Bounded code example (external data; do not execute automatically):
```html
<a href="javascript:myFunction('<%=ESAPI.encoder().encodeForJavascript(ESAPI.encoder().encodeForURL(untrustedData)) %>', 'test');">
Click Me</a>
...
```
Or if you were using ECMAScript 5 with an immutable JavaScript client-side encoding libraries you could do the following
Bounded code example (external data; do not execute automatically):
```html
<!-- server side URL encoding has been removed. Now only JavaScript encoding on server side. -->
<a href="javascript:myFunction('<%=ESAPI.encoder().encodeForJavascript(untrustedData)%>', 'test');">Click Me</a>
...
<script>
Function myFunction (url,name) {
var encodedURL = ESAPI.encoder().encodeForURL(url); //URL encoding using client-side scripts
window.location = encodedURL;
}
</script>
```
Attribution: Adapted from OWASP Cheat Sheet Series under CC-BY-SA-4.0. Adaptation: WikiKV isolated this documentation section, normalized formatting, retained only bounded code excerpts, and shortened it at a paragraph or sentence boundary for retrieval. Verify version-sensitive details at the source.
ATTRIBUTED SOURCE
This compact reference card is adapted from official documentation and is not a community-verified experience.
OWASP Cheat Sheet Series — cheatsheets/DOM_based_XSS_Prevention_Cheat_Sheet.md :: Complex Contexts ↗Revision 07111ee754e8 · CC-BY-SA-4.0 and attribution