Back

Why Doesn't <script> Execute? (HTML Entities and XSS Defense)

If you type <script>alert('hacked');</script> into a comment box on a website, what happens?

On most secure websites, the script doesn't execute; instead, the text string is displayed exactly as typed.

Browsers normally interpret < as the start of a tag. So how do they know to display it as text instead of executing it as code?

The secret lies in HTML Entities.

1. The Reserved Character Dilemma

In HTML, characters like <, >, &, and " have special meanings. These are called Reserved Characters.

If you want to write the equation "3 < 5" in your content and type it as is, the browser might get confused, trying to interpret what follows < as a tag.

Therefore, we need a special code to represent these reserved characters "literally."

2. Common HTML Entities

HTML Entities start with & and end with ;.

  • < (Less Than) -> &lt;
  • > (Greater Than) -> &gt;
  • & (Ampersand) -> &amp;
  • " (Double Quote) -> &quot;
  • ' (Single Quote) -> &#39; (or &apos;)
  • Space -> &nbsp; (Non-Breaking Space)

When you see < on the screen, the actual HTML source code is likely &lt;.

3. Defending Against XSS (Cross Site Scripting)

HTML Entities are crucial for security.

XSS is an attack where a hacker injects malicious scripts into a website to steal user cookies or perform harmful actions.

However, if the server converts (escapes) < to &lt; and > to &gt; when saving or displaying user input, what happens?

The browser sees &lt;script&gt; and decides, "This is just text, not a tag," and renders it as text without executing the script. This is the most fundamental and powerful defense against XSS.

Conclusion

Modern frontend frameworks like React or Vue automatically escape data by default when rendering.

However, when using features like dangerouslySetInnerHTML, this automatic defense is disabled. In such cases, you must ensure that HTML entity conversion has been applied.

A simple character conversion acts as a shield protecting your website from hacking.

TechHTMLSecurityWeb

Explore Related Tools

Try these free developer tools from Pockit