Skip to main content

HTML Security: Keeping Pages and Visitors Safe

A web page is a conversation between your site, your visitors, and a crowd of other parties: browsers, third-party scripts, embedded content, and people who would like to misuse any of them. Security is the habit of deciding who is allowed to do what on your page, and making the browser enforce it.

HTML cannot make a site secure by itself. But HTML decides what a page loads, what it embeds, how it links to other sites, and how it collects information, and each of those is a place where things go wrong or are done safely. This section teaches the HTML-level protections, and is honest about which protections belong on the server.

What You Will Learn​

  • Where web page security problems come from
  • The three rules behind almost every defence
  • The main threats: XSS, risky embeds, tab hijacking, mixed content, and unsafe forms
  • Which HTML features and attributes defend against each
  • Which defences are HTTP headers set on the server, not tags in your page
  • What HTML can never do for you
  • How to pick the right defence for a given risk

The Big Idea​

Most security problems on web pages share one root cause: something untrusted is given more power than it should have. A visitor's comment becomes code. A third-party widget can read the whole page. A link gives another site control of your tab. The defences all do the same thing in different ways: reduce what untrusted things can do.

index.html
<!-- 1. A link that opens another site safely -->
<a href="https://partner.example.com" target="_blank" rel="noopener noreferrer">Our partner</a>

<!-- 2. A third-party embed with its powers switched off -->
<iframe
src="https://widgets.example.com/map"
sandbox="allow-scripts"
title="Map to the bakery"
width="600" height="400" loading="lazy"></iframe>

<!-- 3. A form that sends data safely (the page itself must be https) -->
<form action="/signup" method="post">
<label for="email">Email</label>
<input id="email" name="email" type="email" autocomplete="email" required>
<label for="password">Password</label>
<input id="password" name="password" type="password" autocomplete="new-password" required>
<button type="submit">Sign up</button>
</form>

<!-- 4. A third-party script that must match a known fingerprint -->
<script src="https://cdn.example.com/lib.js"
integrity="sha384-REPLACE_WITH_REAL_HASH"
crossorigin="anonymous" defer></script>

In the lab, leave the sample comment as it is and switch between the two modes. In unsafe mode, a comment that looks like a friendly message contains an element with an event handler. In escaped mode, the same text is only text. That difference is the foundation of the next lessons.

Three Rules Behind Almost Every Defence​

  1. Never trust input. Anything that comes from outside your own code can be wrong or hostile: form fields, URLs, query strings, cookies, files, other sites, and the output of third-party scripts.
  2. Escape for the place the data goes. Text inserted into HTML, into an attribute, into a URL, and into JavaScript each needs its own kind of escaping. Use the browser's safe methods and your framework's defaults, and avoid building markup out of strings.
  3. Give the least power that works. Sandbox embeds, restrict where scripts may come from, ask for only the permissions you need, and use https. No single layer is perfect, so use several (this is called defence in depth).

Where the Risks Come From​

ThreatWhat it isMain defenceLesson
Cross-site scripting (XSS)Untrusted text becomes code running in your pageEscape output, avoid unsafe insertion, add a CSPXSS Basics
Risky embedsA third-party frame or widget does more than you intendedsandbox, limited permissions, trusted sourcesiFrame Security, Sandbox
Tab hijackingA page you open can redirect your original tabrel="noopener"noopener
Leaking where visitors came fromThe destination learns the full previous addressrel="noreferrer", referrer policynoreferrer
Injected or untrusted scripts and stylesCode from unexpected hosts runsContent Security Policy, integrity hashesContent Security Policy
Mixed contentAn https page loads http resourcesUse https for everythingMixed Content
Unsafe formsSensitive data is sent or handled carelesslyhttps, correct input types, server checksSecure Forms

Who Sets What: HTML or the Server?​

Some protections are tags and attributes in your page. Others are HTTP headers, sent by the server before the page. A header cannot be set from inside the HTML (with a few limited exceptions), so you need to know which is which.

ProtectionWhere it livesNotes
Escaping outputYour code (server or browser)The most important defence against XSS
rel="noopener", rel="noreferrer"HTML attributeOn links and forms that open new pages
sandbox on an iframeHTML attributeRestricts what the embedded page can do
integrity on scripts and stylesHTML attributeChecks a file matches a known hash
Content Security PolicyHTTP header, or a meta tag with limitsThe header is preferred and more complete
https and redirectsServer or hosting setupNot something HTML can switch on
Cookie flags (Secure, HttpOnly, SameSite)HTTP headerSet when the server creates the cookie
Who may embed your pageHTTP headerSet with frame-ancestors in a CSP
Input validation and authorisationServer codeThe browser's checks are never enough

If you use a static host or a platform such as Netlify, Vercel, or GitHub Pages, headers are usually set in a configuration file or the platform's settings. Check your host's documentation.

What HTML Can Never Do for You​

warning

Attributes such as required, maxlength, pattern, type="email", hidden, disabled, and readonly are conveniences for honest visitors. Anyone can bypass them with developer tools or by sending requests directly. They are not security. Every rule that matters must also be checked on the server.

  • HTML cannot hide secrets. Anything in the page source, including comments and hidden fields, is readable by anyone.
  • HTML cannot authenticate or authorise anyone. Deciding who may see or do something is the server's job.
  • HTML cannot make an insecure connection secure. That needs https on the server.
  • HTML cannot clean up untrusted data on its own. You must escape or sanitise it where it is used.

Pick the Right Defence​

Match each situation to the defence that fits it best, then check your answers.

http://127.0.0.1:5500/index.html







What Is in This Section​

Some of these topics already have an introduction in earlier lessons: Link Security, Third-Party Content Security, and Secure Form Design. The lessons here go deeper, one topic at a time, and link back to those.

Good Habits to Start With​

  1. Escape output by default, and let your framework or template engine do it.
  2. Add rel="noopener" to links that open in a new tab (and noreferrer when privacy calls for it).
  3. Use https everywhere, for the page and for every file it loads.
  4. Treat every embed and third-party script as a guest. Give it only the power it needs.
  5. Check on the server every rule you check in the browser.
  6. Keep secrets out of the page, including comments, hidden fields, and public code.
  7. Keep software and libraries updated, and remove what you no longer use.

A Ten-Minute Security Check​

Run through this on any page you are about to publish. The full list is in the last lesson, HTML Security Checklist.

  • The page and all its files load over https
  • Visitor-supplied text is escaped wherever it is shown
  • Links with target="_blank" have rel="noopener"
  • Every iframe is from a trusted source, and sandboxed where possible
  • Third-party scripts are few, trusted, and use integrity when the file is fixed
  • Forms use https, the right input types, and server-side checks
  • No secrets, keys, or private notes appear in the page source
  • The server sends the security headers you rely on

Practise Responsibly​

  • Test only what you own, or have written permission to test. Probing other people's sites can be illegal, even with good intentions.
  • The demos in this section are inert. They analyse text without running it. Keep your own experiments in a local or throwaway project.
  • If you find a problem on someone else's site, report it privately to the owner. Many sites publish a contact in a security.txt file at /.well-known/security.txt, and you can offer one on your own site too.
  • Collecting less data is a security measure. Information you never stored cannot leak.
  • Never put real passwords, keys, or personal data into examples, screenshots, or public repositories.

Global Audience Notes​

  • Threats and good practice are the same everywhere, but the rules that apply to you may not be. Laws about data, consent, and breach reporting differ between countries. This section is not legal advice, so check the rules for the places your visitors live.
  • Visitors use shared and public computers. Do not turn off password managers, and use the right autocomplete values, so people can use strong, unique passwords without typing them on a stranger's keyboard.
  • Slow and unreliable networks are common. Make sure security features do not depend on a heavy script that may never load.
  • Names and addresses use many scripts. Look-alike characters from different alphabets can make a malicious web address resemble a trusted one. Show visitors the real destination of a link where it matters.
  • Error messages should be clear in the visitor's language without revealing details an attacker could use, such as which half of a login was wrong.
  • Security must stay accessible. Prefer verification methods that work with screen readers and keyboards over puzzles that exclude people.

Common Mistakes to Avoid​

  1. Treating HTML attributes as security, such as required, hidden, or maxlength.
  2. Building markup out of strings that include visitor text.
  3. Trusting content because it came from your own database. It may have started as visitor input.
  4. Opening external links in a new tab with no rel.
  5. Embedding third-party content with no sandbox and no limits.
  6. Loading any resource over http on an https page.
  7. Putting keys, tokens, or passwords in the page or public code.
  8. Copying a security snippet without understanding what it does.
  9. Relying on one layer. If a single defence fails, nothing else protects you.
  10. Never testing. Many protections fail quietly.

Practice Time​

  1. In the Escaping Lab, leave the sample as it is and switch modes. What changes?
  2. Change the comment to plain text. What does unsafe mode show now?
  3. Add a link with href="javascript:..." to the comment. What does the lab flag?
  4. Take the defence matcher quiz. Which two defences did you confuse?
  5. Look at the source of a page you built. Is there anything in a comment or a hidden field that should not be public?
  6. Find every target="_blank" link on a page. Which lack rel?
  7. Open DevTools on a page of yours, and look at the Network panel. Does anything load over http?
  8. Bonus: open the Network panel and look at the response headers of your home page. Which security headers does your site send?

Quick Recap​

Click a question to check your answer.

1. What is the root cause of most web page security problems?

Something untrusted is given more power than it should have, such as visitor text becoming code, an embed reading the whole page, or a link controlling your tab.

2. What are the three rules behind most defences?

Never trust input, escape for the place the data goes, and give the least power that works, using several layers.

3. Is required or maxlength a security feature?

No. They are conveniences for honest visitors. Anyone can bypass them, so the server must check every rule that matters.

4. Which defences are HTTP headers rather than HTML?

Cookie flags, frame-ancestors, and the full Content Security Policy are set by the server. Escaping, rel values, sandbox, and integrity are in your HTML or code.

5. What does escaping do?

It turns characters that have a special meaning in HTML, such as the angle brackets and quotes, into harmless text, so visitor input cannot create elements or code.

6. Why use more than one defence?

Any single protection can fail or be bypassed. Layers mean that when one fails, another still limits the damage.

Key Takeaways​

  • Security is about limiting what untrusted things can do.
  • Escape output, give least power, and layer your defences.
  • HTML provides some defences, such as rel, sandbox, and integrity, and the server provides others, such as headers and https.
  • Browser-side checks are conveniences, not security. Always check on the server.
  • Embeds, third-party scripts, and links are the places to be careful.
  • Collect less, expose less, and test your own work.

Start with HTML Security Basics, and work through the lessons in order.