Can an HTML <script> fragment on the URL be used for XSS in a purely client side application?

Say I have the following webpage:

<html>
  
    document.write('querystring=' + location.search.substr(1));
  
<html>

I open it at a URL like this:

http://completely-secure-site/?alert('fsecurity')

In all browsers tried (Chrome 57, Firefox 52 and Safari 10) the result is:

querystring=%3Cscript%3Ealert(%27hi%27)%3C/script%3E

Because angle brackets <> are not valid URL characters they seem to be automatically encoded by the browser.

This leads me to believe that simply rendering the querystring directly on the client using document.write is safe, and not a possible XSS vector. (I realize that there are many other ways in which an app can be vulnerable of course, but let’s stick to the precise case described here.)

My question: Am I correct in my assumption? Is the encoding of unsafe characters in the URL in some way standardized or mandated across all reasonable browsers? Or, is this just a nicety / implementation detail of certain (modern?) clients on which I shouldn’t rely?


Not relevant to the question, but an interesting aside. If I decode the URI first then browser behavior is different: document.write(decodeURI(location.search.substr(1)));. The XSS Auditor in both Chrome and Safari blocks the page, while Firefox shows the alert.


Source: stackoverflow-javascript