Cross-Site Scripting (XSS)

Learn the differences between nonpersistent and persistent Cross-Site Scripting and how to prevent these kinds of attacks.

Injection

Ranked number seven on the OWASP Top 10 in 2017 as a stand-alone category, Cross-Site Scripting (XSS) is the unwanted injection of client-side code into a website. In 2022, OWASP recategorized XSS into the broader Injection category, which now sits in the number three spot—a clear indication of how important it is to prevent.

Where does JavaScript come from?

When a user loads a web page for this course, the client sends an HTTP request to an educative.io server, and it returns HTML. Once the browser receives the HTML document, it then constructs a DOM tree out of it. The DOM (Document Object Model) is a way to represent the structure and content of a web page document using a tree data structure. Every single piece of a document, including each HTML element, attribute, and text content, represents a DOM node and is part of the Document Object Model. It can also be accessed and manipulated with Web APIs via JavaScript.

During HTML parsing and DOM construction, the browser determines if it needs to fetch any additional resources including CSS, JavaScript, and images. If external resources are in the document, perhaps via a script tag with an src attribute, for example <script src="/myCoolScript.js"></script>, the browser requests each one from the server and downloads it. Maybe the script tag doesn't have an src attribute, and the JavaScript is nested directly inside the tags, for example, <script>console.log('hi')</script>. If the browser encounters a script tag, DOM construction will pause until the script finishes loading and executing since JavaScript can alter the DOM. However, this behavior can be changed with async or defer attributes on script tags that fetch external resources.

Note: It's normal to see several network requests for JavaScript assets when a modern web application is initially loaded.

As an exercise, open the JavaScript console in a web browser, select the “Network” tab, filter for “JS” requests only, and refresh this page.

Get hands-on with 1200+ tech skills courses.