diff --git a/tutorials/html/16-security/content-security-policy.mdx b/tutorials/html/16-security/content-security-policy.mdx
new file mode 100644
index 000000000..6f81c1f68
--- /dev/null
+++ b/tutorials/html/16-security/content-security-policy.mdx
@@ -0,0 +1,576 @@
+---
+id: html-sec-content-security-policy
+title: "Content Security Policy (CSP)"
+sidebar_label: "Content Security Policy"
+sidebar_position: 8
+slug: /html/security/content-security-policy
+description: "Learn how a Content Security Policy tells the browser which sources of scripts, styles, images, frames and forms to trust. Covers directives, source values, nonces, report-only rollout, and the meta tag's limits, with a live policy tester and a directive matcher."
+keywords:
+ - content security policy
+ - CSP header
+ - CSP meta tag
+ - script-src
+ - default-src
+ - nonce
+ - unsafe-inline
+ - frame-ancestors
+ - report-only
+ - learn HTML
+ - CodeHarborHub HTML
+tags: [html, web-development, beginner, security, csp, xss, headers, frontend]
+---
+
+import {useState} from 'react';
+
+export const cspPage = "https://www.example.com/";
+
+export const cspResources = [
+ {id: "r1", label: "Inline script in the page", dir: "script-src", kind: "inline"},
+ {id: "r2", label: 'Inline script with nonce="r4nd0m"', dir: "script-src", kind: "inline", nonce: "r4nd0m"},
+ {id: "r3", label: "onclick attribute on a button", dir: "script-src", kind: "attr"},
+ {id: "r4", label: "Script from /app.js (your site)", dir: "script-src", kind: "url", url: "https://www.example.com/app.js"},
+ {id: "r5", label: "Script from cdn.example.net", dir: "script-src", kind: "url", url: "https://cdn.example.net/lib.js"},
+ {id: "r6", label: "Stylesheet from /site.css (your site)", dir: "style-src", kind: "url", url: "https://www.example.com/site.css"},
+ {id: "r7", label: "style attribute on an element", dir: "style-src", kind: "attr"},
+ {id: "r8", label: "Image from /logo.png (your site)", dir: "img-src", kind: "url", url: "https://www.example.com/logo.png"},
+ {id: "r9", label: "Image from images.example.org", dir: "img-src", kind: "url", url: "https://images.example.org/photo.jpg"},
+ {id: "r10", label: "Image as a data: address", dir: "img-src", kind: "url", url: "data:image/png;base64,AAAA"},
+ {id: "r11", label: "Font from fonts.example.com", dir: "font-src", kind: "url", url: "https://fonts.example.com/body.woff2"},
+ {id: "r12", label: "Frame from widgets.example.net", dir: "frame-src", kind: "url", url: "https://widgets.example.net/map"},
+ {id: "r13", label: "fetch() call to api.example.com", dir: "connect-src", kind: "url", url: "https://api.example.com/data"}
+];
+
+export const cspPresets = {
+ none: "",
+ starter: "default-src 'self'; img-src 'self' https://images.example.org data:; font-src https://fonts.example.com; frame-src https://widgets.example.net; connect-src 'self' https://api.example.com; object-src 'none'; base-uri 'self'; frame-ancestors 'self'",
+ nonce: "default-src 'self'; script-src 'self' 'nonce-r4nd0m'; style-src 'self'; img-src 'self' https://images.example.org data:; font-src https://fonts.example.com; frame-src https://widgets.example.net; connect-src 'self' https://api.example.com; object-src 'none'; base-uri 'self'; frame-ancestors 'self'",
+ loose: "default-src *; script-src * 'unsafe-inline' 'unsafe-eval' data:"
+};
+
+export function parseCsp(text) {
+ const map = Object.create(null);
+ text.split(";").forEach(function (part) {
+ const t = part.trim().split(/\s+/).filter(Boolean);
+ if (t.length === 0) return;
+ const name = t[0].toLowerCase();
+ if (!(name in map)) map[name] = t.slice(1);
+ });
+ return map;
+}
+
+export function sourceMatches(src, urlText, pageText) {
+ let u;
+ let page;
+ try {
+ u = new URL(urlText, pageText);
+ page = new URL(pageText);
+ } catch (e) {
+ return false;
+ }
+ const s = src.trim();
+ const low = s.toLowerCase();
+ if (low === "'none'") return false;
+ if (low === "*") return ["http:", "https:", "ws:", "wss:"].indexOf(u.protocol) !== -1;
+ if (low === "'self'") return u.origin === page.origin;
+ if (/^[a-z][a-z0-9+.-]*:$/.test(low)) return u.protocol === low || (low === "http:" && u.protocol === "https:");
+ if (low.charAt(0) === "'") return false;
+ let rest = low;
+ let scheme = null;
+ const sm = rest.match(/^([a-z][a-z0-9+.-]*):\/\//);
+ if (sm) {
+ scheme = sm[1] + ":";
+ rest = rest.slice(sm[0].length);
+ }
+ rest = rest.split("/")[0];
+ let port = null;
+ const pm = rest.match(/:(\d+|\*)$/);
+ if (pm) {
+ port = pm[1];
+ rest = rest.slice(0, rest.length - pm[0].length);
+ }
+ if (scheme) {
+ if (!(u.protocol === scheme || (scheme === "http:" && u.protocol === "https:"))) return false;
+ } else if (u.protocol !== page.protocol && u.protocol !== "https:") {
+ return false;
+ }
+ let hostOk;
+ if (rest === "*") hostOk = true;
+ else if (rest.indexOf("*.") === 0) hostOk = u.hostname.length > rest.length - 1 && u.hostname.slice(-(rest.length - 1)) === rest.slice(1);
+ else hostOk = u.hostname === rest;
+ if (!hostOk) return false;
+ if (port && port !== "*") return u.port === port;
+ return true;
+}
+
+export function resourceAllowed(res, sources) {
+ if (res.kind === "url") {
+ return sources.some(function (s) { return sourceMatches(s, res.url, cspPage); });
+ }
+ const lower = sources.map(function (s) { return s.toLowerCase(); });
+ const hasNonceOrHash = lower.some(function (s) { return /^'(nonce-|sha(256|384|512)-)/.test(s); });
+ if (res.kind === "inline" && res.nonce && lower.indexOf("'nonce-" + res.nonce.toLowerCase() + "'") !== -1) return true;
+ return lower.indexOf("'unsafe-inline'") !== -1 && !hasNonceOrHash;
+}
+
+export function evaluateCsp(text) {
+ const map = parseCsp(text);
+ return cspResources.map(function (res) {
+ let via = null;
+ let sources = null;
+ if (map[res.dir]) { via = res.dir; sources = map[res.dir]; }
+ else if (map["default-src"]) { via = "default-src"; sources = map["default-src"]; }
+ if (sources === null) return {res: res, allowed: true, via: "no rule"};
+ return {res: res, allowed: resourceAllowed(res, sources), via: via};
+ });
+}
+
+export function lintCsp(text) {
+ const map = parseCsp(text);
+ const out = [];
+ const scriptSources = (map["script-src"] || map["default-src"] || null);
+ const lower = (scriptSources || []).map(function (s) { return s.toLowerCase(); });
+ const hasNonce = lower.some(function (s) { return /^'(nonce-|sha(256|384|512)-)/.test(s); });
+ if (text.trim() === "") {
+ out.push({level: "problem", text: "No policy: the browser applies no restrictions."});
+ return out;
+ }
+ if (scriptSources === null) out.push({level: "problem", text: "No script-src or default-src, so scripts are unrestricted."});
+ if (lower.indexOf("'unsafe-inline'") !== -1 && !hasNonce) out.push({level: "problem", text: "'unsafe-inline' in the script rules lets injected inline scripts run, which removes most of CSP's protection against XSS."});
+ if (lower.indexOf("'unsafe-inline'") !== -1 && hasNonce) out.push({level: "tip", text: "Browsers ignore 'unsafe-inline' when a nonce or hash is present. It is only a fallback for very old browsers."});
+ if (/'unsafe-eval'/i.test(text)) out.push({level: "problem", text: "'unsafe-eval' allows eval and similar functions to turn text into code."});
+ if (lower.indexOf("*") !== -1 || lower.indexOf("https:") !== -1 || lower.indexOf("http:") !== -1) out.push({level: "problem", text: "A wildcard or a bare scheme in the script rules lets almost any site supply scripts."});
+ if (lower.indexOf("data:") !== -1) out.push({level: "problem", text: "data: in the script rules lets attackers run scripts written straight into an address."});
+ if (!map["object-src"] && !(map["default-src"] && map["default-src"].map(function (s) { return s.toLowerCase(); }).indexOf("'none'") !== -1)) out.push({level: "tip", text: "Add object-src 'none' to switch off old plugin content."});
+ if (!map["base-uri"]) out.push({level: "tip", text: "Add base-uri 'self' so an injected base tag cannot redirect your relative links."});
+ if (!map["frame-ancestors"]) out.push({level: "tip", text: "Add frame-ancestors (as a header) to control who may frame your pages."});
+ if (out.length === 0) out.push({level: "good", text: "No warnings from this simple check."});
+ return out;
+}
+
+export function CspTester() {
+ const [text, setText] = useState(cspPresets.starter);
+ const rows = evaluateCsp(text);
+ const lint = lintCsp(text);
+ const blocked = rows.filter(function (r) { return !r.allowed; }).length;
+ const colors = {problem: "#c0392b", tip: "#b9770e", good: "#1e8449"};
+ const labels = {problem: "Problem", tip: "Tip", good: "Good"};
+ return (
+
+
Your page is {cspPage}. Edit the policy, or load an example.
+
+
+
+
+
+
+
+
+
+
+
+
What the page tries to load
+
Result
+
Decided by
+
+
+
+ {rows.map(function (r) {
+ return (
+
+
{r.res.label}
+
{r.allowed ? "Allowed" : "Blocked"}
+
{r.via}
+
+ );
+ })}
+
+
+
{blocked} of {rows.length} blocked.
+
+ {lint.map(function (f, i) {
+ return (
+
+ {labels[f.level]}: {f.text}
+
+ );
+ })}
+
+
+ A simplified model. It handles the common sources (self, none, hosts, schemes, nonces, unsafe-inline) and ignores paths, hashes, strict-dynamic and the more specific directives. Nothing here loads a real resource.
+
+
+ );
+}
+
+export const dirOptions = [
+ "script-src", "style-src", "img-src", "connect-src", "frame-src", "frame-ancestors", "base-uri", "form-action", "object-src", "upgrade-insecure-requests"
+];
+
+export const dirItems = [
+ {goal: "Which hosts my page may load scripts from", answer: "script-src"},
+ {goal: "Which hosts my page may put inside frames", answer: "frame-src"},
+ {goal: "Which sites may put MY page inside a frame", answer: "frame-ancestors"},
+ {goal: "Where fetch and XMLHttpRequest may send requests", answer: "connect-src"},
+ {goal: "Stop an injected base tag from changing relative links", answer: "base-uri"},
+ {goal: "Where my forms may submit to", answer: "form-action"},
+ {goal: "Ask the browser to load http subresources over https", answer: "upgrade-insecure-requests"},
+ {goal: "Switch off old plugin content such as object and embed", answer: "object-src"}
+];
+
+export function DirectiveMatcher() {
+ const [picked, setPicked] = useState({});
+ const [checked, setChecked] = useState(false);
+ const correct = dirItems.filter(function (it, i) { return picked[i] === it.answer; }).length;
+ return (
+
+ );
+}
+
+Most of this section is about what **you** write in HTML. A **Content Security Policy** is different. It is a set of rules you give the browser, telling it **which sources it may trust** for scripts, styles, images, frames, and more. If an attacker manages to slip a script into your page, CSP can stop the browser from running it.
+
+CSP does not replace good habits like escaping, as taught in [XSS Basics](./xss-basics). It is a **second layer** that limits the damage when something goes wrong.
+
+## What You Will Learn
+
+- What a Content Security Policy is, and how a browser applies it
+- How to send one as a header, and what the `meta` tag can and cannot do
+- The main directives and source values
+- Why inline scripts are blocked, and how nonces fix that safely
+- How to roll out a policy without breaking your site
+- What CSP does not do
+
+
+
+
+## The Big Idea
+
+Without CSP, the browser runs any script on the page, whoever put it there. With CSP, the browser first checks a **guest list**. A script, image, or frame is loaded only if its source is on the list for that kind of content.
+
+
+
+
+```text title="Response header (recommended)"
+Content-Security-Policy: default-src 'self'; img-src 'self' https://images.example.org; frame-ancestors 'self'; object-src 'none'; base-uri 'self'
+```
+
+```html title="index.html (limited: the meta tag)"
+
+
+
+```
+
+
+
+
+
+<>
+
+>
+
+
+
+
+
+
+<>
+
+>
+
+
+
+
+
+## Header or Meta Tag?
+
+The proper way is an **HTTP response header** set by your server or hosting service.
+
+You can also put a policy in a `meta` tag with `http-equiv="Content-Security-Policy"`, which is useful when you cannot set headers, such as on a simple static host. But a `meta` policy has real limits:
+
+| | Header | `meta` tag |
+| :-- | :-- | :-- |
+| Covers content loaded **before** the tag | Yes | No. It must appear early in the `head`, and it affects only what comes after |
+| `frame-ancestors` | Works | **Ignored** |
+| `sandbox` directive | Works | **Ignored** |
+| Reporting directives | Work | **Ignored** |
+| Report-only mode | Yes | No |
+
+If your host lets you set headers (many have a settings page or a headers file), prefer the header.
+
+## How a Policy Is Written
+
+A policy is a list of **directives** separated by semicolons. Each directive has a name and a list of allowed **sources**:
+
+```text
+script-src 'self' https://cdn.example.net; img-src *.example.org data:
+```
+
+### The most useful directives
+
+| Directive | Controls |
+| :-- | :-- |
+| `default-src` | A fallback for most fetch directives that you do not set yourself |
+| `script-src` | JavaScript, including inline scripts and event attributes |
+| `style-src` | Stylesheets, `style` elements, and `style` attributes |
+| `img-src`, `font-src`, `media-src` | Images, fonts, audio and video |
+| `connect-src` | `fetch`, `XMLHttpRequest`, WebSocket, and similar connections |
+| `frame-src` | Where **your** page may load frames from |
+| `frame-ancestors` | Who may put **your** page in a frame (replaces the old `X-Frame-Options` idea; see [iFrame Security](./iframe-security)) |
+| `object-src` | Plugin content (`object`, `embed`). Set to `'none'` |
+| `base-uri` | What a `base` tag may set. Use `'self'` |
+| `form-action` | Where forms may submit to (see [Secure Forms](./secure-forms)) |
+| `upgrade-insecure-requests` | Ask the browser to load `http` subresources over `https` (see [Mixed Content](./mixed-content)) |
+| `sandbox` | Applies sandbox rules to the page (see [Sandbox Attribute](./sandbox-attribute)) |
+
+:::info
+`default-src` is a **fallback** only for the fetch-type directives (scripts, styles, images, fonts, frames, connections, and so on). It does **not** cover `base-uri`, `form-action`, or `frame-ancestors`. Set those yourself.
+:::
+
+### Source values
+
+| Source | Meaning |
+| :-- | :-- |
+| `'self'` | Your own origin |
+| `'none'` | Nothing at all |
+| `https://cdn.example.net` | That exact host |
+| `*.example.org` | Any subdomain of that host (not the bare domain) |
+| `https:` | Any `https` address (very broad) |
+| `data:` | `data:` addresses (fine for small images, dangerous for scripts) |
+| `'nonce-...'` | An inline element carrying the matching `nonce` |
+| `'sha256-...'` | An inline script or style whose text hashes to this value |
+| `'unsafe-inline'` | Any inline code. Weakens protection |
+| `'unsafe-eval'` | `eval` and similar. Weakens protection |
+
+Note the **quotes**. Keywords such as `'self'` and `'none'` must be written with single quotes inside the policy, while hosts and schemes are not quoted.
+
+## Try It: The Policy Tester
+
+Open the **Policy Tester** tab. It lists thirteen things a page might try to load. Pick **Starter policy** and read the results:
+
+- Scripts from your own site are allowed, but the inline script and the `onclick` attribute are **blocked**. That is CSP doing its job.
+- A script from `cdn.example.net` is blocked, because it is not on the list.
+
+Now load **Strict, with a nonce**, and compare. Then load **Too loose**, and read the warnings.
+
+## Inline Scripts: Why They Are Blocked
+
+By default, a useful CSP blocks **inline scripts and event attributes**. This is deliberate, because injected XSS is usually an inline script. The cost is that you must move your own code into files, and replace `onclick="..."` attributes with `addEventListener`.
+
+```html
+
+
+
+
+
+
+```
+
+If you must keep a specific inline script, use a **nonce** or a **hash**, never `'unsafe-inline'`.
+
+### Nonces
+
+A nonce is a random value that the server generates for **each response**. It appears in the header and on the trusted script:
+
+```text
+Content-Security-Policy: script-src 'self' 'nonce-r4nd0m'
+```
+
+```html
+
+```
+
+An injected script has no way to know the nonce, so it is blocked. Three rules make this safe:
+
+1. **Generate a new, unpredictable value for every response,** on the server, with a secure random generator.
+2. **Never reuse a nonce,** and never use a fixed one. `r4nd0m` above is only a teaching placeholder.
+3. **A nonce needs a server** that builds the page. A fully static page cannot use one. For that case, use a hash, or move scripts to files.
+
+When a policy contains a nonce or a hash, browsers **ignore** `'unsafe-inline'` in that directive. The Policy Tester shows this in action.
+
+## Rolling Out a Policy Safely
+
+A strict policy can break pages in ways you do not expect. Roll it out in steps:
+
+1. **Start in report-only mode.** Send `Content-Security-Policy-Report-Only` with the same policy. The browser reports what **would** have been blocked, without blocking anything. Reports go to an endpoint you set up with a reporting directive (check your provider's current documentation for the exact setup).
+2. **Watch the Console.** Chrome, Firefox, and Safari show CSP violations in DevTools, naming the directive and the blocked source.
+3. **Fix the cause.** Move inline code into files, add the hosts you really use, and remove the ones you do not.
+4. **Switch to enforcing** by sending `Content-Security-Policy`. You can send both headers while you tune a stricter version.
+5. **Keep watching.** New scripts, new third-party tools, and new embeds all need a policy update.
+
+Several policies can be sent at once, and the browser applies **all** of them. A resource must pass every one.
+
+## A Starter Policy
+
+This is a reasonable starting point for a simple site that serves its own scripts and styles. Adjust the hosts to match what your page really uses:
+
+```text
+Content-Security-Policy:
+ default-src 'self';
+ img-src 'self' data: https://images.example.org;
+ frame-src https://widgets.example.net;
+ connect-src 'self';
+ object-src 'none';
+ base-uri 'self';
+ form-action 'self';
+ frame-ancestors 'self'
+```
+
+If your site uses inline `style` attributes or `style` elements, CSP will block them. Moving styles into a stylesheet is the best fix, and a nonce or hash for a specific `style` element is the next best. Avoid giving up with `'unsafe-inline'` in `style-src` unless you accept the trade-off.
+
+## What CSP Does Not Do
+
+- **It is not a replacement for escaping and sanitising.** It is a safety net. See [XSS Basics](./xss-basics).
+- **It cannot stop a script you allowed,** from a host you trust, from misbehaving. If a trusted host is hacked, your site is affected.
+- **It does not stop all attacks,** such as phishing links, or abuse of a legitimate feature of your own site.
+- **It does not hide anything from the visitor.** It restricts what the browser loads, and does not encrypt or conceal.
+- **Wide wildcards weaken it.** A policy that allows `https:` for scripts allows scripts from almost anywhere.
+
+:::warning
+Do not copy a long policy from the internet without understanding it. An overly loose policy gives a false sense of safety, and an overly strict one breaks your site. Start from your actual needs, test in report-only mode, and tighten step by step.
+:::
+
+## Checking Your Setup
+
+1. Open DevTools, then **Network**, click the page request, and read **Response Headers**. Is `Content-Security-Policy` there?
+2. Open the **Console** and reload. CSP violations appear as red messages naming the directive.
+3. Test every feature: menus, forms, embeds, analytics, fonts, and maps.
+4. Run your policy through a CSP evaluator tool from a reputable source, and treat its output as advice, not a verdict.
+5. Review the policy whenever you add a new third-party service.
+
+## Best Practices
+
+1. **Prefer a header** to a `meta` tag.
+2. **Start with `default-src 'self'`,** then add only what you need.
+3. **Set `object-src 'none'`, `base-uri 'self'`,** and `frame-ancestors`.
+4. **Move inline scripts to files,** or use nonces or hashes.
+5. **Avoid `'unsafe-inline'` and `'unsafe-eval'`** in script rules.
+6. **Do not allow `data:` or wildcards** for scripts.
+7. **Roll out in report-only mode** first.
+8. **List hosts as exactly as you can,** rather than whole schemes.
+9. **Review the policy** when your page changes.
+10. **Keep escaping and sanitising** as your main defence.
+
+## Quick Checklist
+
+- [ ] A policy is sent as a header (or a `meta` tag as a fallback)
+- [ ] `default-src` is set to something narrow
+- [ ] `script-src` has no `'unsafe-inline'`, `'unsafe-eval'`, wildcards, or `data:`
+- [ ] `object-src 'none'`, `base-uri`, and `frame-ancestors` are set
+- [ ] Inline code uses nonces or hashes, or lives in files
+- [ ] You tested in report-only mode first
+- [ ] The Console shows no unexpected violations
+
+## Security and Privacy Notes
+
+- **Reports can contain page addresses.** If you collect violation reports, they may include URLs that hold personal information. Store them carefully, and keep them only as long as needed.
+- **Third-party hosts you allow can see your visitors.** Each host in your policy is a company that receives requests from your visitors' browsers. Allow as few as possible.
+- **A nonce is only secret within one response.** Never put it in a place that is cached and shared between visitors.
+- **Test only your own site,** or sites you have permission to test.
+
+## Global Audience Notes
+
+- **Different regions use different services,** such as maps, payments, and fonts. A policy that works at home can block a service your visitors in another country use, so test with real flows.
+- **CDNs and fonts can be slow or blocked** in some places. Serving fonts and scripts from your own origin is simpler for a policy, and often faster.
+- **Error messages from CSP are in English** in DevTools. Make sure your team can read them, and that visitor-facing errors on your site remain in the page's own language.
+
+## Common Mistakes to Avoid
+
+1. **Adding `'unsafe-inline'`** to make a problem go away.
+2. **Forgetting the quotes** around `'self'` or `'none'`.
+3. **Assuming `default-src` covers `frame-ancestors`,** `base-uri`, and `form-action`.
+4. **Putting `frame-ancestors` in a `meta` tag,** where it is ignored.
+5. **Whitelisting whole schemes** such as `https:`.
+6. **Reusing or hard-coding a nonce.**
+7. **Skipping report-only mode** and breaking the live site.
+8. **Allowing a host and never reviewing** it again.
+9. **Treating CSP as a substitute** for escaping input and output.
+10. **Copying a policy** you do not understand.
+
+## Practice Time
+
+1. In the Policy Tester, load **No policy**. How many items are blocked? What does the warning say?
+2. Load **Starter policy**. Which scripts are blocked, and why?
+3. Add `https://cdn.example.net` to `script-src` in the Starter policy. What changes?
+4. Load **Strict, with a nonce**. Which inline script is now allowed? Is the `onclick` attribute?
+5. Add `'unsafe-inline'` to the nonce policy's `script-src`. Does the `onclick` attribute start working? Why not?
+6. Load **Too loose**, and list the warnings it gives.
+7. Complete the Directive Matcher.
+8. Bonus: open DevTools on a site you own, read its `Content-Security-Policy` header, and explain each directive in your own words.
+
+## Quick Recap
+
+Click a question to check your answer.
+
+
+1. What is a Content Security Policy?
+
+A set of rules, sent as a header (or a `meta` tag), that tells the browser which sources it may load scripts, styles, images, frames, and more from.
+
+
+
+
+2. Why is a header better than a `meta` tag?
+
+A `meta` policy only affects what follows it, and ignores `frame-ancestors`, `sandbox`, and reporting directives. A header covers the whole page and supports all directives.
+
+
+
+
+3. What does `default-src` do?
+
+It is a fallback for most fetch directives you do not set. It does not cover `base-uri`, `form-action`, or `frame-ancestors`.
+
+
+
+
+4. Why are inline scripts blocked?
+
+Injected XSS is usually an inline script. Blocking inline code stops it. Your own code goes in files, or uses a nonce or hash.
+
+
+
+
+5. What makes a nonce safe?
+
+It is unpredictable, generated by the server for each response, and never reused, so an attacker cannot guess it.
+
+
+
+
+6. How do you roll out a policy safely?
+
+Start in report-only mode, read the violations, fix their causes, then enforce. Keep monitoring as the site changes.
+
+
+
+## Key Takeaways
+
+- **CSP is a guest list for the browser.** It limits where content may come from.
+- **Send it as a header.** The `meta` tag is a limited fallback.
+- **Start with `default-src 'self'`,** then add what you truly need.
+- **Avoid `'unsafe-inline'`, `'unsafe-eval'`, `data:`, and wildcards** for scripts.
+- **Use nonces or hashes** for the inline code you must keep.
+- **Roll out in report-only mode,** then enforce.
+- **CSP is a second layer.** Escaping and sanitising remain the first.
+
+Next up: [Mixed Content](./mixed-content), where you will learn what happens when a secure page loads something over plain `http`, and how browsers and policies deal with it.
\ No newline at end of file
diff --git a/tutorials/html/16-security/html-security-basics.mdx b/tutorials/html/16-security/html-security-basics.mdx
new file mode 100644
index 000000000..dc37935a3
--- /dev/null
+++ b/tutorials/html/16-security/html-security-basics.mdx
@@ -0,0 +1,551 @@
+---
+id: html-sec-basics
+title: "HTML Security Basics"
+sidebar_label: "HTML Security Basics"
+sidebar_position: 2
+slug: /html/security/html-security-basics
+description: "Learn the foundations of HTML security: what an origin is, what the same-origin policy protects, how to find the doors into your page, and why https and server-side checks matter. Includes an origin comparison lab and a page survey tool."
+keywords:
+ - HTML security basics
+ - same-origin policy
+ - what is an origin
+ - attack surface
+ - web security for beginners
+ - https
+ - third-party scripts
+ - client side vs server side security
+ - learn HTML
+ - CodeHarborHub HTML
+tags: [html, web-development, beginner, security, same-origin-policy, https, attack-surface, frontend]
+---
+
+import {useState} from 'react';
+import BrowserOnly from '@docusaurus/BrowserOnly';
+
+export function originOf(url) {
+ try {
+ const u = new URL(url);
+ const port = u.port || (u.protocol === "https:" ? "443" : u.protocol === "http:" ? "80" : "");
+ return {ok: true, scheme: u.protocol.replace(":", ""), host: u.hostname, port: port};
+ } catch (e) {
+ return {ok: false};
+ }
+}
+
+export function compareOrigins(a, b) {
+ const x = originOf(a);
+ const y = originOf(b);
+ if (!x.ok || !y.ok) return {ok: false};
+ const scheme = x.scheme === y.scheme;
+ const host = x.host === y.host;
+ const port = x.port === y.port;
+ return {ok: true, x: x, y: y, scheme: scheme, host: host, port: port, same: scheme && host && port};
+}
+
+export function OriginLab() {
+ const [a, setA] = useState("https://shop.example.com/menu");
+ const [b, setB] = useState("https://shop.example.com/cart");
+ const r = compareOrigins(a, b);
+ const presets = [
+ ["Different path", "https://shop.example.com/cart"],
+ ["Different scheme", "http://shop.example.com/menu"],
+ ["Different subdomain", "https://api.example.com/menu"],
+ ["Different port", "https://shop.example.com:8443/menu"],
+ ["Different domain", "https://example.org/menu"]
+ ];
+ const cell = function (match) {
+ return
{match ? "Same" : "Different"}
;
+ };
+ return (
+
+
+
+
+
+
+
+
+
+
+
+
+ {presets.map(function (p) {
+ return ;
+ })}
+
+ {r.ok ? (
+
+
+
+
+
Part
+
Page A
+
Page B
+
Result
+
+
+
+
Scheme
{r.x.scheme}
{r.y.scheme}
{cell(r.scheme)}
+
Host
{r.x.host}
{r.y.host}
{cell(r.host)}
+
Port
{r.x.port}
{r.y.port}
{cell(r.port)}
+
+
+
+ {r.same
+ ? "Same origin. Scripts on one page can read the other page's content and responses."
+ : "Different origins. The browser stops scripts on one from reading the other, unless the other site explicitly allows it."}
+
+
+ ) : (
+
Enter two full addresses, such as https://example.com/page.
+ )}
+
+ An origin is the scheme, the host, and the port. The path never matters. When no port is written, https means 443 and http means 80.
+
+
+ );
+}
+
+export const surveySamples = {
+ messy: [
+ '',
+ '',
+ '',
+ 'Our partner',
+ 'Open',
+ '',
+ '',
+ '',
+ ''
+ ].join("\n"),
+ fixed: [
+ '',
+ 'Our partner',
+ '',
+ '',
+ '',
+ ''
+ ].join("\n")
+};
+
+export function surveyPage(html, pageOrigin) {
+ const doc = new DOMParser().parseFromString(html, "text/html");
+ let base;
+ try {
+ base = new URL(pageOrigin);
+ } catch (e) {
+ return {ok: false};
+ }
+ const secure = base.protocol === "https:";
+ const abs = function (v) {
+ try { return new URL(v, base); } catch (e) { return null; }
+ };
+ const findings = [];
+ const add = function (level, text) { findings.push({level: level, text: text}); };
+ const scripts = Array.from(doc.querySelectorAll("script"));
+ const external = scripts.filter(function (s) { return s.hasAttribute("src"); });
+ const inlineScripts = scripts.length - external.length;
+ const thirdParty = external.filter(function (s) { const u = abs(s.getAttribute("src")); return u && u.origin !== base.origin; });
+ const noIntegrity = thirdParty.filter(function (s) { return !s.hasAttribute("integrity"); });
+ if (noIntegrity.length > 0) add("tip", noIntegrity.length + " third-party script(s) have no integrity hash. That is normal for files that change often, but you are trusting that host completely.");
+ else if (thirdParty.length > 0) add("good", "Every third-party script has an integrity hash.");
+ const handlers = Array.from(doc.querySelectorAll("*")).filter(function (el) {
+ return Array.from(el.attributes).some(function (a) { return a.name.toLowerCase().indexOf("on") === 0; });
+ });
+ if (handlers.length > 0) add("tip", handlers.length + " element(s) use inline event handlers such as onclick. They work, but they make a strict Content Security Policy harder. Use addEventListener instead.");
+ if (inlineScripts > 0) add("tip", inlineScripts + " inline script(s). A strict Content Security Policy needs these to be moved out, or marked with a nonce or hash.");
+ const insecure = Array.from(doc.querySelectorAll("[src], link[href]")).filter(function (el) {
+ const v = el.getAttribute("src") || el.getAttribute("href");
+ const u = abs(v);
+ return secure && u && u.protocol === "http:";
+ });
+ if (insecure.length > 0) add("problem", insecure.length + " file(s) load over http on an https page. This is mixed content. Use https for every file.");
+ const frames = Array.from(doc.querySelectorAll("iframe"));
+ const openFrames = frames.filter(function (f) { return !f.hasAttribute("sandbox"); });
+ if (openFrames.length > 0) add("tip", openFrames.length + " iframe(s) have no sandbox attribute, so the embedded page keeps all its normal powers.");
+ else if (frames.length > 0) add("good", "Every iframe is sandboxed.");
+ const blanks = Array.from(doc.querySelectorAll('a[target="_blank"]')).filter(function (a) {
+ const rel = (a.getAttribute("rel") || "").toLowerCase();
+ return rel.indexOf("noopener") === -1 && rel.indexOf("noreferrer") === -1;
+ });
+ if (blanks.length > 0) add("tip", blanks.length + " link(s) open a new tab with no rel. Current major browsers add noopener for you, but older ones do not, and it costs nothing to be explicit.");
+ const jsLinks = Array.from(doc.querySelectorAll("a[href]")).filter(function (a) { return a.getAttribute("href").trim().toLowerCase().indexOf("javascript:") === 0; });
+ if (jsLinks.length > 0) add("problem", jsLinks.length + " link(s) use a javascript: address. Use a button with an event listener instead.");
+ const forms = Array.from(doc.querySelectorAll("form"));
+ const insecureForms = forms.filter(function (f) { const u = abs(f.getAttribute("action") || ""); return secure && u && u.protocol === "http:"; });
+ if (insecureForms.length > 0) add("problem", insecureForms.length + " form(s) send data to an http address. Always send form data over https.");
+ const passwords = Array.from(doc.querySelectorAll('input[type="password"]'));
+ const getPassword = passwords.filter(function (p) { const f = p.closest("form"); return f && (f.getAttribute("method") || "get").toLowerCase() === "get"; });
+ if (getPassword.length > 0) add("problem", getPassword.length + " password field(s) are in a form that uses GET, which puts the values in the address. Use method=\"post\".");
+ const noAuto = passwords.filter(function (p) { return !p.hasAttribute("autocomplete"); });
+ if (noAuto.length > 0) add("tip", noAuto.length + " password field(s) have no autocomplete value. Use current-password or new-password so password managers work.");
+ if (findings.length === 0) add("good", "No doors worth flagging in this snippet.");
+ return {
+ ok: true,
+ counts: {scripts: external.length, thirdParty: thirdParty.length, inlineScripts: inlineScripts, iframes: frames.length, forms: forms.length, passwords: passwords.length},
+ findings: findings
+ };
+}
+
+export function SurveyInner() {
+ const [html, setHtml] = useState(surveySamples.messy);
+ const [origin, setOrigin] = useState("https://www.example.com");
+ const r = surveyPage(html, origin);
+ const colors = {problem: "#c0392b", tip: "#b9770e", good: "#1e8449"};
+ const labels = {problem: "Problem", tip: "Tip", good: "Good"};
+ return (
+
+
+
+
+
+
+
+
+
+
+
+
+ {r.ok ? (
+
+
The doors in this page
+
+
{r.counts.scripts} external script(s), {r.counts.thirdParty} from other origins, and {r.counts.inlineScripts} inline
+
{r.counts.iframes} iframe(s)
+
{r.counts.forms} form(s), with {r.counts.passwords} password field(s)
+
+
+ {r.findings.map(function (f, i) {
+ return (
+
+ {labels[f.level]}:
+ {f.text}
+
+ );
+ })}
+
+
+ ) : (
+
Enter your page's full address, such as https://www.example.com.
+ )}
+
+ This is a teaching survey. It reads markup only, so it cannot see your server, your headers, or what scripts do. A clean result does not mean a page is secure.
+
+
+ );
+}
+
+export function PageSurvey() {
+ return (
+ Loading the survey...}>
+ {function () { return ; }}
+
+ );
+}
+
+Before learning the specific protections, you need a picture of what you are protecting and from whom. This lesson builds that picture. It explains the one rule that the browser enforces for you, the same-origin policy, and the many things it does not stop, then shows you how to find the doors into your own pages so you know where to look.
+
+## What You Will Learn
+
+- What an origin is, and what the same-origin policy protects
+- What the policy does **not** protect you from
+- How to think about threats in four simple questions
+- The "doors" into a web page: inputs, includes, links, outputs, and storage
+- Why `https` comes first
+- What the browser can enforce, and what only the server can
+- The main families of web vulnerabilities, in plain terms
+
+
+
+
+## The Big Idea
+
+A web page is a small building with many doors. Some let visitors in (forms and links). Some let other people's code in (scripts, iframes, fonts). Some send information out (form submissions, requests). Security begins with knowing where all the doors are, and making sure each one has the right lock.
+
+
+
+
+```html title="index.html"
+
+
+
+
+
+
+
+Our partner
+
+
+
+
+
+
+
+
+
+```
+
+
+
+
+
+<>
+
+>
+
+
+
+
+
+
+<>
+
+>
+
+
+
+
+
+In the Origin Lab, press each preset and watch which part changes. In the Page Survey, load the messy page, read what it finds, and then load the fixed page to compare. You will meet every fix in the lessons that follow.
+
+## What Is an Origin?
+
+An **origin** is three things taken together: the **scheme** (`https`), the **host** (`shop.example.com`), and the **port** (`443`). Two addresses have the same origin only if all three match. The path (`/menu`, `/cart`) never matters.
+
+| Address | Same origin as `https://shop.example.com/menu`? | Why |
+| :-- | :-- | :-- |
+| `https://shop.example.com/cart` | Yes | Only the path differs |
+| `http://shop.example.com/menu` | No | Different scheme |
+| `https://api.example.com/menu` | No | Different host (a subdomain counts) |
+| `https://shop.example.com:8443/menu` | No | Different port |
+| `https://example.org/menu` | No | Different domain |
+
+## The Same-Origin Policy
+
+The **same-origin policy** is the browser's most important built-in protection. In simple terms: **a script running on one origin cannot read the pages or responses of another origin.**
+
+Without it, any site you visited could quietly read your email in another tab. With it, a page on `evil.example` cannot reach into `mail.example` just because you have both open. Storage such as `localStorage` is also kept separate for each origin. (Cookies follow slightly different rules, based on the host and their own settings, so they are covered in the server-side lessons.)
+
+The policy has a deliberate exception for **sending**: a page may freely *include* other origins' files and *send* requests to them. It cannot, by default, *read* what comes back. A server can choose to relax this using a mechanism called CORS, which is a topic for server-side learning.
+
+## What the Policy Does Not Protect You From
+
+This is the part most beginners miss. The same-origin policy protects origins **from each other**. It does not protect you from things you invite in yourself.
+
+- **A script you include runs as your page.** If you add `
```
- ├── 16-security/
- │ ├── index.mdx
- │ ├── html-security-basics.mdx
- │ ├── xss-basics.mdx
- │ ├── iframe-security.mdx
- │ ├── sandbox-attribute.mdx
- │ ├── noreferrer.mdx
- │ ├── noopener.mdx
- │ ├── content-security-policy.mdx
- │ ├── mixed-content.mdx
- │ ├── secure-forms.mdx
- │ └── html-security-checklist.mdx
-```
\ No newline at end of file
+
+
+
+
+
+<>
+
+>
+
+
+
+
+
+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
+
+| Threat | What it is | Main defence | Lesson |
+| :-- | :-- | :-- | :-- |
+| Cross-site scripting (XSS) | Untrusted text becomes code running in your page | Escape output, avoid unsafe insertion, add a CSP | [XSS Basics](./security/xss-basics) |
+| Risky embeds | A third-party frame or widget does more than you intended | `sandbox`, limited permissions, trusted sources | [iFrame Security](./security/iframe-security), [Sandbox](./security/sandbox-attribute) |
+| Tab hijacking | A page you open can redirect your original tab | `rel="noopener"` | [noopener](./security/noopener) |
+| Leaking where visitors came from | The destination learns the full previous address | `rel="noreferrer"`, referrer policy | [noreferrer](./security/noreferrer) |
+| Injected or untrusted scripts and styles | Code from unexpected hosts runs | Content Security Policy, integrity hashes | [Content Security Policy](./security/content-security-policy) |
+| Mixed content | An https page loads http resources | Use https for everything | [Mixed Content](./security/mixed-content) |
+| Unsafe forms | Sensitive data is sent or handled carelessly | https, correct input types, server checks | [Secure Forms](./security/secure-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.
+
+| Protection | Where it lives | Notes |
+| :-- | :-- | :-- |
+| Escaping output | Your code (server or browser) | The most important defence against XSS |
+| `rel="noopener"`, `rel="noreferrer"` | HTML attribute | On links and forms that open new pages |
+| `sandbox` on an iframe | HTML attribute | Restricts what the embedded page can do |
+| `integrity` on scripts and styles | HTML attribute | Checks a file matches a known hash |
+| Content Security Policy | HTTP header, or a `meta` tag with limits | The header is preferred and more complete |
+| `https` and redirects | Server or hosting setup | Not something HTML can switch on |
+| Cookie flags (`Secure`, `HttpOnly`, `SameSite`) | HTTP header | Set when the server creates the cookie |
+| Who may embed your page | HTTP header | Set with `frame-ancestors` in a CSP |
+| Input validation and authorisation | Server code | The 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.
+
+
+<>
+
+>
+
+
+## What Is in This Section
+
+Some of these topics already have an introduction in earlier lessons: [Link Security](/tutorials/html/links-and-navigation/link-security), [Third-Party Content Security](/tutorials/html/embedded-content/third-party-content-security), and [Secure Form Design](/tutorials/html/forms/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](./security/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](./security/html-security-basics), and work through the lessons in order.
\ No newline at end of file
diff --git a/tutorials/html/16-security/mixed-content.mdx b/tutorials/html/16-security/mixed-content.mdx
new file mode 100644
index 000000000..20868beff
--- /dev/null
+++ b/tutorials/html/16-security/mixed-content.mdx
@@ -0,0 +1,491 @@
+---
+id: html-sec-mixed-content
+title: "Mixed Content"
+sidebar_label: "Mixed Content"
+sidebar_position: 9
+slug: /html/security/mixed-content
+description: "Learn what mixed content is, why an https page that loads anything over http is unsafe, how browsers treat active and passive content, and how to fix it with https URLs, upgrade-insecure-requests and HSTS. Includes a mixed content lab and a markup finder."
+keywords:
+ - mixed content
+ - https http mixed content
+ - upgrade-insecure-requests
+ - Strict-Transport-Security
+ - HSTS
+ - active mixed content
+ - passive mixed content
+ - secure context
+ - learn HTML
+ - CodeHarborHub HTML
+tags: [html, web-development, beginner, security, https, mixed-content, headers, frontend]
+---
+
+import {useState} from 'react';
+import BrowserOnly from '@docusaurus/BrowserOnly';
+
+export const mixedResources = [
+ {id: "m1", label: "Photo", type: "image", kind: "passive", url: "http://images.example.org/photo.jpg", hostHttps: true},
+ {id: "m2", label: "Old banner", type: "image", kind: "passive", url: "http://old-ads.example.org/banner.gif", hostHttps: false},
+ {id: "m3", label: "Video clip", type: "video", kind: "passive", url: "http://media.example.net/clip.mp4", hostHttps: true},
+ {id: "m4", label: "Analytics script", type: "script", kind: "active", url: "http://stats.example.net/tracker.js", hostHttps: true},
+ {id: "m5", label: "Legacy widget script", type: "script", kind: "active", url: "http://widgets.example.org/widget.js", hostHttps: false},
+ {id: "m6", label: "Stylesheet", type: "stylesheet", kind: "active", url: "http://cdn.example.net/theme.css", hostHttps: true},
+ {id: "m7", label: "Map frame", type: "iframe", kind: "active", url: "http://maps.example.net/embed", hostHttps: true},
+ {id: "m8", label: "fetch() to an API", type: "fetch", kind: "active", url: "http://api.example.com/data", hostHttps: true},
+ {id: "m9", label: "Live updates socket", type: "WebSocket", kind: "active", url: "ws://live.example.com/feed", hostHttps: true},
+ {id: "m10", label: "Logo", type: "image", kind: "passive", url: "https://www.example.com/logo.png", hostHttps: true},
+ {id: "m11", label: "Local test script", type: "script", kind: "active", url: "http://127.0.0.1:5500/dev.js", hostHttps: false}
+];
+
+export function mixedOutcome(pageScheme, res, upgrade) {
+ let u;
+ try {
+ u = new URL(res.url);
+ } catch (e) {
+ return {state: "bad", text: "Invalid address"};
+ }
+ if (pageScheme === "http") return {state: "ok", text: "Loads (but the page itself is not secure)"};
+ if (u.protocol === "https:" || u.protocol === "wss:") return {state: "ok", text: "Loads securely"};
+ if (u.hostname === "127.0.0.1" || u.hostname === "localhost") return {state: "ok", text: "Loads (local addresses are treated as trustworthy)"};
+ if (upgrade) {
+ return res.hostHttps
+ ? {state: "ok", text: "Upgraded to https, and loads"}
+ : {state: "bad", text: "Upgraded to https, then fails (the host has no https)"};
+ }
+ if (res.kind === "active") return {state: "bad", text: "Blocked"};
+ return res.hostHttps
+ ? {state: "warn", text: "Browser tries an https upgrade, and it loads"}
+ : {state: "bad", text: "Blocked (the https upgrade failed)"};
+}
+
+export function MixedLab() {
+ const [pageScheme, setPageScheme] = useState("https");
+ const [upgrade, setUpgrade] = useState(false);
+ const rows = mixedResources.map(function (r) { return {res: r, out: mixedOutcome(pageScheme, r, upgrade)}; });
+ const failed = rows.filter(function (r) { return r.out.state === "bad"; }).length;
+ const colors = {ok: "#1e8449", warn: "#b9770e", bad: "#c0392b"};
+ return (
+
+
+
+
+
+
+
Resource
+
Kind
+
What happens
+
+
+
+ {rows.map(function (r) {
+ return (
+
+
{r.res.label} ({r.res.type}) {r.res.url}
+
{r.res.kind}
+
{r.out.text}
+
+ );
+ })}
+
+
+
{failed} of {rows.length} would fail to load.
+
+ A simplified model. Exact behaviour differs a little between browsers and versions, and nothing here loads a real address. The fix is not the header: it is to use https addresses, with the header as a safety net.
+
+
+ );
+}
+
+export const findSamples = {
+ messy: [
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ 'Partner',
+ '',
+ ''
+ ].join("\n"),
+ fixed: [
+ '',
+ '',
+ '',
+ '',
+ '',
+ 'Partner'
+ ].join("\n")
+};
+
+export function findMixed(html) {
+ const doc = new DOMParser().parseFromString(html, "text/html");
+ const out = [];
+ const isInsecure = function (v) { return /^\s*(http|ws):\/\//i.test(v || ""); };
+ const isLocal = function (v) { return /^\s*(http|ws):\/\/(127\.0\.0\.1|localhost)(:|\/|$)/i.test(v || ""); };
+ Array.from(doc.querySelectorAll("[src],[href],[action],[data],[poster],[srcset]")).forEach(function (el) {
+ const tag = el.tagName.toLowerCase();
+ const rel = (el.getAttribute("rel") || "").toLowerCase();
+ ["src", "href", "action", "data", "poster", "srcset"].forEach(function (attr) {
+ if (!el.hasAttribute(attr)) return;
+ const value = el.getAttribute(attr);
+ const parts = attr === "srcset" ? value.split(",").map(function (p) { return p.trim().split(/\s+/)[0]; }) : [value];
+ parts.forEach(function (part) {
+ const label = tag + " " + attr + '="' + part + '"';
+ if (/^\s*\/\//.test(part)) {
+ out.push({level: "tip", text: label + ": a protocol-relative address. It follows the page's scheme, but write https:// so it is clear."});
+ return;
+ }
+ if (!isInsecure(part)) return;
+ if (isLocal(part)) {
+ out.push({level: "tip", text: label + ": a local address. Browsers treat it as trustworthy, but remove it before publishing."});
+ return;
+ }
+ if (tag === "a" && attr === "href") {
+ out.push({level: "tip", text: label + ": a link, not mixed content, but it sends visitors to an insecure page. Use https if the site supports it."});
+ } else if (tag === "form" && attr === "action") {
+ out.push({level: "problem", text: label + ": a form that would submit over http. Browsers warn about this, and it exposes what visitors type."});
+ } else if (tag === "link" && rel.indexOf("stylesheet") === -1 && rel.indexOf("preload") === -1 && rel.indexOf("modulepreload") === -1) {
+ out.push({level: "tip", text: label + ": a link element. Use https."});
+ } else if (["img", "audio", "video", "source", "track"].indexOf(tag) !== -1 || attr === "poster") {
+ out.push({level: "tip", text: label + ": passive mixed content. Browsers try to upgrade it, and may block it."});
+ } else {
+ out.push({level: "problem", text: label + ": active mixed content. Browsers block it."});
+ }
+ });
+ });
+ });
+ if (out.length === 0) out.push({level: "good", text: "No http:// or ws:// addresses found in the attributes checked."});
+ return out;
+}
+
+export function FinderInner() {
+ const [html, setHtml] = useState(findSamples.messy);
+ const findings = findMixed(html);
+ const colors = {problem: "#c0392b", tip: "#b9770e", good: "#1e8449"};
+ const labels = {problem: "Problem", tip: "Tip", good: "Good"};
+ return (
+
+
Imagine this markup is on a page served over https.
+
+
+
+
+
+
+
+ {findings.map(function (f, i) {
+ return (
+
+ {labels[f.level]}: {f.text}
+
+ );
+ })}
+
+
+ A teaching checker. It reads attributes only. It cannot see addresses created by JavaScript, or inside CSS files, so also check the browser Console on the real page.
+
+
+ );
+}
+
+export function MixedFinder() {
+ return (
+ Loading the checker...}>
+ {function () { return ; }}
+
+ );
+}
+
+Imagine you post a letter in a locked, tamper-proof envelope, but inside it you tuck a note that says "also fetch this parcel from the corner stall", and the stall is open for anyone to swap the parcel. The envelope was secure. The parcel was not.
+
+That is **mixed content**: a page delivered over secure `https` that loads some of its parts over plain `http`. The secure part is only as safe as the weakest part.
+
+## What You Will Learn
+
+- What mixed content is, and why it is dangerous
+- The difference between active and passive mixed content
+- What browsers block, upgrade, or warn about
+- How to find mixed content on a page
+- How to fix it, with `https` addresses first, and a header as a safety net
+- What HSTS adds
+
+
+
+
+## The Big Idea
+
+`https` protects a connection from being read or changed on its way. Any part of your page loaded over `http` has **no such protection**, and anyone on the path, such as a person on the same public Wi-Fi, can read it or **swap it for something else**.
+
+
+
+
+```html title="Mixed content (do not do this)"
+
+
+
+```
+
+```html title="Fixed"
+
+
+```
+
+```text title="Safety net: response header"
+Content-Security-Policy: upgrade-insecure-requests
+```
+
+
+
+
+
+<>
+
+>
+
+
+
+
+
+
+<>
+
+>
+
+
+
+
+
+## Why It Is Dangerous
+
+What an attacker can do depends on what the page loaded:
+
+- **A script over `http`:** the attacker can replace it with their own. That script then runs **inside your secure page**, with full access to it, including forms, cookies that are not `HttpOnly`, and everything the visitor sees. This is as bad as XSS, and it does not need any bug in your code.
+- **A stylesheet over `http`:** it can hide parts of the page, or reposition a fake form over the real one.
+- **An iframe over `http`:** the attacker can show a fake page inside your page.
+- **An image or video over `http`:** it can be swapped for misleading content, and visitors can be tracked, since the request is visible.
+- **A form that submits over `http`:** everything the visitor typed travels unprotected.
+
+## Active and Passive Mixed Content
+
+Browsers split mixed content into two groups, based on how much damage it can do:
+
+| | Passive (display) | Active |
+| :-- | :-- | :-- |
+| **What it is** | Content that is shown but cannot change the page | Content that can run or restructure the page |
+| **Examples** | Images, audio, video | Scripts, stylesheets, iframes, `fetch` and `XMLHttpRequest`, fonts, WebSockets (`ws://`) |
+| **Risk** | Lower, but still tamperable and trackable | High: full takeover is possible |
+| **Typical browser behaviour** | Tries to **upgrade** to `https`, and blocks it if that fails | **Blocked** |
+
+Browsers have also been getting stricter over time, and the details differ a little between them. Do not rely on "the browser will fix it". Treat every `http` address on an `https` page as a bug.
+
+### Links and forms are different
+
+A normal link to an `http` page is **not** mixed content, because the visitor is navigating there, not loading it into your page. But it still takes them to an insecure page, so use `https` when the destination supports it.
+
+A **form** on an `https` page that submits to an `http` address is a different problem. Browsers show warnings, and may block it, because what the visitor types is sent without protection. See [Secure Forms](./secure-forms).
+
+## Finding Mixed Content
+
+1. **Open the Console.** On a page served over `https`, DevTools prints messages beginning "Mixed Content:" that name the blocked or upgraded address.
+2. **Check the Network panel,** and filter by the address starting with `http:`.
+3. **Search your source code** for `http://` and `ws://`. Check templates, stylesheets (`url(...)`), JavaScript strings, and your database content.
+4. **Use the Finder tab above** on your own markup.
+5. **Check old content.** Posts and pages written years ago often hold hard-coded `http://` image links.
+
+## Fixing It
+
+### Step 1: Serve your own site over https
+
+Your site needs a valid certificate. Many hosts provide this automatically, and free certificate services exist. Redirect every `http` request to the `https` version of the same address.
+
+### Step 2: Use https addresses
+
+Change `http://` to `https://` for every resource. Most reputable hosts support it. If a host does not, **stop using that host**, copy the file to your own site if the licence allows, or find an alternative.
+
+### Step 3: Prefer relative addresses for your own files
+
+For files on your own site, use paths such as `/images/photo.jpg`. A relative address always follows the page's scheme, so it cannot be mixed content.
+
+```html
+
+```
+
+You may still see old protocol-relative addresses such as `//cdn.example.net/lib.js`. They work, but writing `https://` is clearer, because every site should be on `https` now.
+
+### Step 4: Add the safety net
+
+The CSP directive `upgrade-insecure-requests` tells the browser to **rewrite `http` subresource addresses to `https`** before loading them:
+
+```text
+Content-Security-Policy: upgrade-insecure-requests
+```
+
+It is useful when you have a lot of old content to clean up. But it is a **net, not a cure**:
+
+- If the host does **not** support `https`, the upgraded request simply **fails**.
+- It hides the problem. Your source code still contains `http://`, and a header change, or a different server, may expose it again.
+
+Open the lab, switch the checkbox on and off, and compare the "Legacy widget script" row. Fix the addresses, then keep the header as a backup. Do not use it as a substitute for fixing them.
+
+### Step 5: Add HSTS, carefully
+
+`Strict-Transport-Security` (HSTS) tells the browser: "for the next while, always use `https` for my site, even if someone types `http://`":
+
+```text
+Strict-Transport-Security: max-age=31536000; includeSubDomains
+```
+
+:::warning
+HSTS is hard to undo, because browsers remember it for the length of `max-age`. Turn it on **only after** your whole site, including subdomains, works over `https`. Start with a short `max-age`, such as a day, test, and raise it step by step. Treat the `preload` option as a long-term commitment, and read the current requirements before using it.
+:::
+
+### Step 6: Add integrity for third-party files
+
+For scripts and styles from other hosts, the `integrity` attribute lets the browser check that the file is exactly the one you reviewed. It needs `crossorigin` for cross-origin files. Details and cautions are in [Third-Party Content Security](/tutorials/html/embedded-content/third-party-content-security).
+
+```html
+
+```
+
+## A Few Related Points
+
+- **WebSockets:** use `wss://`, not `ws://`, on an `https` page.
+- **Local development:** `http://localhost` and `http://127.0.0.1` are treated as trustworthy by browsers, so your local test pages can load local `http` resources. That is why this tutorial's live demos run from an address like `http://127.0.0.1:5500`. Do not leave those addresses in published pages.
+- **Secure contexts:** many powerful features only work on `https` pages (and local addresses), such as location, the camera, service workers, and the clipboard. A site that is not on `https` loses these. This ties to the [HTML Security Basics](./html-security-basics) lesson on the https-first rule.
+- **Browser labels:** pages served over `http` are marked "Not secure" in current browsers, and visitors notice.
+
+## Checking Your Setup
+
+1. Load your page over `https`, open the **Console**, and reload. There should be no "Mixed Content" messages.
+2. In **Network**, filter by `http:` and confirm nothing is listed.
+3. Visit the `http` version of your address. It should redirect to `https`.
+4. Inspect the **Response Headers** for `Strict-Transport-Security` and `Content-Security-Policy`.
+5. Search your content database for `http://`, and update old links.
+6. Test with a private window, in case a browser extension is hiding a problem.
+
+## Best Practices
+
+1. **Serve the whole site over https,** and redirect `http` to it.
+2. **Use `https://` or relative addresses** for every resource.
+3. **Treat any `http://` on a secure page as a bug,** even if a browser upgrades it.
+4. **Drop hosts that do not support https.**
+5. **Add `upgrade-insecure-requests`** as a safety net, not a cure.
+6. **Enable HSTS** only when everything works, and raise it gradually.
+7. **Use `wss://`** for WebSockets.
+8. **Clean old content,** especially hard-coded image links.
+9. **Add `integrity`** to third-party scripts and styles.
+10. **Remove local development addresses** before you publish.
+
+## Quick Checklist
+
+- [ ] The site has a valid certificate, and `http` redirects to `https`
+- [ ] No `http://` or `ws://` addresses in HTML, CSS, JavaScript, or content
+- [ ] Forms submit to `https` or relative addresses
+- [ ] The Console shows no "Mixed Content" messages
+- [ ] `upgrade-insecure-requests` is set as a backup
+- [ ] HSTS is set only after testing
+- [ ] Third-party files use `https`, and ideally `integrity`
+- [ ] No local addresses are left in published pages
+
+## Security and Privacy Notes
+
+- **Insecure requests leak information.** An `http` request shows the address, and often the referrer, to anyone on the path. See [noreferrer](./noreferrer).
+- **A padlock is not a guarantee of a safe site.** It says the connection is encrypted, not that the page is trustworthy. Mixed content weakens even that.
+- **Public Wi-Fi is where this attack happens.** Visitors in cafes, airports, and shared networks are the most exposed.
+- **Certificates need renewal.** An expired certificate breaks your whole site and teaches visitors to click through warnings. Automate renewal, and monitor it.
+
+## Global Audience Notes
+
+- **Some networks and older devices are slow to adapt.** Older phones may not trust newer certificates, and some regions still have many `http`-only services. Test on realistic devices, and have a plan if a partner site has no `https`.
+- **Shared and public networks** are more common in some regions, which makes `https` everywhere more important there.
+- **Interrupted connections** can cause partial loads. A page that mixes secure and insecure resources can break in confusing ways when parts fail. Keep everything on one scheme.
+
+## Common Mistakes to Avoid
+
+1. **Hard-coding `http://`** in templates, stylesheets, or database content.
+2. **Relying on browsers to upgrade** passive content.
+3. **Using `upgrade-insecure-requests` as the only fix,** against a host with no https.
+4. **Enabling HSTS** before everything works on `https`.
+5. **Forgetting `ws://`,** fonts inside CSS, and `fetch` URLs in JavaScript.
+6. **Leaving `localhost` addresses** in a published page.
+7. **Letting a certificate expire.**
+8. **Linking forms to `http` addresses.**
+9. **Ignoring Console warnings** because "the page still looks fine".
+10. **Testing only your own browser,** and not a private window or another device.
+
+## Practice Time
+
+1. In the Mixed Content Lab, keep the page on `https` with the header off. Which resources fail, and which are upgraded?
+2. Switch the header on. Which resources still fail, and why?
+3. Switch the page to `http`. What changes? Is that a good result?
+4. Find the local test script in the table. Why does it load?
+5. Load the messy page in the Mixed Content Finder, and fix every problem until it reports a clean page.
+6. Open any page of your own site, open the Console, and look for "Mixed Content" messages.
+7. Search one of your own templates for `http://`. How many did you find?
+8. Bonus: write the `Strict-Transport-Security` header you would use for your first week of testing.
+
+## Quick Recap
+
+Click a question to check your answer.
+
+
+1. What is mixed content?
+
+A page served over `https` that loads some resources, such as scripts or images, over plain `http`.
+
+
+
+
+2. Why is it dangerous?
+
+Resources loaded over `http` can be read or replaced by anyone on the path. A swapped script runs inside your secure page.
+
+
+
+
+3. What is the difference between active and passive mixed content?
+
+Passive content, such as images and video, is displayed only. Active content, such as scripts, stylesheets, and frames, can run or change the page, so browsers block it.
+
+
+
+
+4. What is the real fix?
+
+Use `https://` or relative addresses for every resource, and serve your own site over `https`.
+
+
+
+
+5. What does `upgrade-insecure-requests` do?
+
+It tells the browser to load `http` subresources over `https`. It is a safety net, and fails when the host does not support `https`.
+
+
+
+
+6. When should you enable HSTS?
+
+Only after the whole site, including subdomains, works over `https`, because browsers remember it for the full `max-age`. Start with a short value.
+
+
+
+## Key Takeaways
+
+- **Mixed content is an `http` resource on an `https` page.** It breaks the protection `https` gives.
+- **Active content is blocked, and passive content may be upgraded or blocked.** Do not depend on either.
+- **Fix addresses first:** `https://` or relative paths.
+- **`upgrade-insecure-requests` is a safety net,** and HSTS is a commitment to apply with care.
+- **Check the Console,** your source, and your old content.
+- **Local addresses are trusted for testing,** but never publish them.
+
+Next up: [Secure Forms](./secure-forms), where you will learn how to protect what visitors type: submission over `https`, safe autofill and password fields, and the checks that belong on the server.
\ No newline at end of file
diff --git a/tutorials/html/16-security/noopener.mdx b/tutorials/html/16-security/noopener.mdx
new file mode 100644
index 000000000..9f0eac833
--- /dev/null
+++ b/tutorials/html/16-security/noopener.mdx
@@ -0,0 +1,456 @@
+---
+id: html-sec-noopener
+title: "noopener and Reverse Tabnabbing"
+sidebar_label: "noopener"
+sidebar_position: 7
+slug: /html/security/noopener
+description: "Learn how window.opener lets a page you open reach back into yours, what reverse tabnabbing is, how rel=noopener and the Cross-Origin-Opener-Policy header close the door, and where browsers already help. Includes an opener lab and a link scanner."
+keywords:
+ - noopener
+ - rel noopener
+ - window.opener
+ - reverse tabnabbing
+ - target _blank security
+ - window.open noopener
+ - Cross-Origin-Opener-Policy
+ - learn HTML
+ - CodeHarborHub HTML
+tags: [html, web-development, beginner, security, links, noopener, tabnabbing, frontend]
+---
+
+import {useState} from 'react';
+import Tabs from '@theme/Tabs';
+import TabItem from '@theme/TabItem';
+import BrowserOnly from '@docusaurus/BrowserOnly';
+import AdsComponent from '@site/src/components/AdsComponent';
+import BrowserWindow from '@site/src/components/BrowserWindow';
+
+export function hasOpener(how, token, browser) {
+ if (token === "noopener" || token === "noreferrer") return false;
+ if (how === "link") {
+ if (token === "opener") return true;
+ return browser === "older";
+ }
+ return true;
+}
+
+export function openerOutcome(has, sameOrigin) {
+ if (!has) {
+ return {level: "safe", text: "window.opener is null in the new page. It has no way to reach your tab."};
+ }
+ if (sameOrigin) {
+ return {level: "danger", text: "The new page is from your own origin, so it has full access to your tab: it can read and change your page, not just redirect it."};
+ }
+ return {level: "danger", text: "The new page can set window.opener.location, and your original tab silently becomes a page of the attacker's choosing, such as a fake sign-in page. It still cannot read your page's content."};
+}
+
+export function OpenerLab() {
+ const [how, setHow] = useState("link");
+ const [token, setToken] = useState("none");
+ const [browser, setBrowser] = useState("modern");
+ const [sameOrigin, setSameOrigin] = useState(false);
+ const [ran, setRan] = useState(false);
+ const has = hasOpener(how, token, browser);
+ const out = openerOutcome(has, sameOrigin);
+ const hijacked = ran && has;
+ const tokenWord = how === "link" ? 'rel="' + token + '"' : '"' + token + '" in the window features';
+ const code = how === "link"
+ ? 'Partner"
+ : 'window.open("https://partner.example.net/", "_blank"' + (token === "none" ? "" : ', "' + token + '"') + ");";
+ const reset = function () { setRan(false); };
+ return (
+
+
+
+
+
+
+
+
{code}
+
+
{hijacked ? "Your original tab: https://login-shop.example.net/signin" : "Your original tab: https://shop.example.com/orders"}
+ A simplified picture drawn with ordinary boxes. Nothing is opened. Setting: {tokenWord}.
+
+
+ );
+}
+
+export const scanSamples = {
+ messy: [
+ 'Partner',
+ 'News',
+ 'Dealer',
+ 'Tools',
+ 'Open',
+ 'About us'
+ ].join("\n"),
+ fixed: [
+ 'Partner',
+ 'News',
+ 'About us'
+ ].join("\n")
+};
+
+export function scanLinks(html) {
+ const doc = new DOMParser().parseFromString(html, "text/html");
+ const els = Array.from(doc.querySelectorAll("a[target], area[target], form[target]"));
+ const out = [];
+ els.forEach(function (el, i) {
+ const tag = el.tagName.toLowerCase();
+ const target = (el.getAttribute("target") || "").toLowerCase();
+ const rel = (el.getAttribute("rel") || "").toLowerCase().split(/\s+/).filter(Boolean);
+ const where = tag + " " + (i + 1) + (el.getAttribute("href") ? " (" + el.getAttribute("href") + ")" : "");
+ const href = (el.getAttribute("href") || "").trim().toLowerCase();
+ if (/^(javascript|data|vbscript):/.test(href)) out.push({level: "problem", text: where + ": the address uses a dangerous scheme. Remove it."});
+ if (target === "_self" || target === "_parent" || target === "_top") return;
+ if (rel.indexOf("opener") !== -1) {
+ out.push({level: "problem", text: where + ': rel="opener" deliberately re-opens window.opener. Remove it unless you truly need it.'});
+ return;
+ }
+ const protectedLink = rel.indexOf("noopener") !== -1 || rel.indexOf("noreferrer") !== -1;
+ if (target === "_blank") {
+ if (!protectedLink) out.push({level: "tip", text: where + ": no noopener. Modern browsers add it for target=_blank, but older ones do not, so add rel=\"noopener\" to be explicit."});
+ else out.push({level: "good", text: where + ": protected."});
+ } else if (target !== "") {
+ if (!protectedLink) out.push({level: "tip", text: where + ': the named window "' + target + '" can be reused and does not get the implied protection that _blank gets. Add rel="noopener" if you do not need a link back.'});
+ }
+ });
+ if (els.length === 0) out.push({level: "good", text: "No links with a target attribute found."});
+ return out;
+}
+
+export function ScannerInner() {
+ const [html, setHtml] = useState(scanSamples.messy);
+ const findings = scanLinks(html);
+ const colors = {problem: "#c0392b", tip: "#b9770e", good: "#1e8449"};
+ const labels = {problem: "Problem", tip: "Tip", good: "Good"};
+ return (
+
+
+
+
+
+
+
+
+ {findings.map(function (f, i) {
+ return (
+
+ {labels[f.level]}: {f.text}
+
+ );
+ })}
+
+
+ A teaching checker. It reads the markup as text and never opens or loads any link.
+
+
+ );
+}
+
+export function LinkScanner() {
+ return (
+ Loading the checker...}>
+ {function () { return ; }}
+
+ );
+}
+
+ When your page opens a new tab, that new page can get a **handle back to yours**. Most of the time nothing bad happens. But when the new page is untrusted, that handle lets it quietly change what your original tab shows. The fix is a single small word, `noopener`.
+
+You met it briefly in [Link Security](/tutorials/html/links-and-navigation/link-security) and [External Links](/tutorials/html/links-and-navigation/external-links). This lesson explains **how the attack works**, what browsers now do for you, and the cases where the old advice still matters.
+
+## What You Will Learn
+
+- What `window.opener` is
+- What reverse tabnabbing is, and what an attacker can and cannot do
+- What `rel="noopener"` does
+- What browsers already do by default, and where that stops
+- How `window.open` and the `Cross-Origin-Opener-Policy` header fit in
+- When you do need the link back to the opener
+
+
+
+
+## The Big Idea
+
+Opening a page with `target="_blank"` or `window.open()` is like handing someone a phone line back to your room. `noopener` cuts the line.
+
+
+
+
+```html title="index.html"
+
+Partner
+
+
+Partner
+```
+
+```js title="script.js"
+// window.open does not get protection by default. Ask for it.
+window.open("https://partner.example.net/", "_blank", "noopener");
+```
+
+
+
+
+
+<>
+
+>
+
+
+
+
+
+
+<>
+
+>
+
+
+
+
+
+## What Is window.opener?
+
+When one page opens another, the new page receives a reference to the page that opened it, called `window.opener`. It is useful for things like login popups that report back to the page that started them.
+
+If the new page was **not** opened this way (for example, the visitor typed the address), `window.opener` is `null`.
+
+## Reverse Tabnabbing
+
+"Tabnabbing" is a trick where a tab you are not looking at changes into something else. In **reverse** tabnabbing, the attack comes through the link the visitor clicked:
+
+1. A visitor is on your page, say an orders page, and clicks a link that opens a new tab to another site.
+2. That site (or a script on it, or a comment link posted by someone else) runs `window.opener.location = "https://login-shop.example.net/signin"`.
+3. The visitor finishes reading the new tab and goes back to your tab. It now shows a **fake sign-in page**, with an address that looks plausible.
+4. They type their password, and the attacker has it.
+
+Open the **Opener Lab** tab, choose the "Older" browser (keep "link" and "nothing"), and press the run button to see this unfold.
+
+### What the new page can and cannot do
+
+| If the opened page is... | It can... | It cannot... |
+| :-- | :-- | :-- |
+| **From another origin** | Set `window.opener.location` (redirect your tab), send `postMessage`, close or focus your tab, and count its frames | Read your page's content or run scripts inside it |
+| **From your own origin** | Everything, including reading and changing your page (see [HTML Security Basics](./html-security-basics)) | Nothing is out of reach |
+
+Even a redirect is serious. Visitors trust the tab they left open, and a convincing fake sign-in page can steal passwords.
+
+## The Fix: rel="noopener"
+
+`rel="noopener"` makes the new page's `window.opener` `null`, so the line back is cut.
+
+```html
+Partner
+```
+
+A few facts that surprise people:
+
+- **It has a speed benefit too.** With no link back, the browser can run the new page separately from yours, so a heavy or slow new page is less likely to drag your page down.
+- **`noreferrer` implies `noopener`.** Using `rel="noreferrer"` closes the line **and** removes the referrer (see [noreferrer](./noreferrer)). Use both words together if you want both effects clearly stated.
+- **It works on `a`, `area`, and `form` elements** that have a `target`.
+- **It has no effect without a new window.** A normal same-tab link does not create an opener.
+
+## What Browsers Already Do
+
+Modern browsers treat `target="_blank"` as if `rel="noopener"` were present. That means the classic attack above no longer works on a current browser for plain links. But you should still add the word, for these reasons:
+
+1. **Older browsers** and some embedded web views do not apply the default.
+2. **Being explicit** makes your intent obvious to the next developer, and to tools that scan your code.
+3. **The default is narrow.** It applies to `_blank`. A link with a custom name, such as `target="popup"`, can reuse an existing named window, and does not get the same automatic protection.
+4. **`window.open()` in JavaScript** does not get it automatically. You must pass `"noopener"` in the features string.
+5. **`rel="opener"` turns it off on purpose.** If you find that word in your code, ask why.
+
+The Opener Lab lets you flip between modern and older browsers and between a link and `window.open`, so you can see where protection depends on the browser.
+
+## window.open and noopener
+
+```js
+const win = window.open("https://partner.example.net/", "_blank", "noopener");
+console.log(win); // null, because the new window has no link to yours
+```
+
+When you pass `"noopener"`, the browser returns `null` instead of a window object. That is expected, so do not treat it as an error. If your code needs to talk to the opened window, you cannot use `noopener`.
+
+## The Header: Cross-Origin-Opener-Policy
+
+Everything above protects **your links**. But what about someone else's page that opens yours? A header can protect your page from that:
+
+```text
+Cross-Origin-Opener-Policy: same-origin
+```
+
+With this header, your page is placed in a separate group from pages of other origins, and any opener relationship across origins is cut, in both directions. Other values, such as `same-origin-allow-popups`, relax this to allow popups you open to keep a link to you.
+
+:::warning
+Some features depend on an opener link, such as certain login and payment popups. Strict settings can break them. Test sign-in and payment flows after you add this header, and read your provider's current guidance. See [Content Security Policy](./content-security-policy) for another header-based layer.
+:::
+
+## When You Do Need the Opener
+
+Sometimes a page really does need to talk to the window it opened, such as a sign-in popup that returns a result. If so:
+
+1. **Open only trusted pages** with `window.opener` intact.
+2. **Use `postMessage` instead of direct access,** and check `event.origin` against an exact value, as shown in [iFrame Security](./iframe-security).
+3. **Never rely on `window.opener` alone** to decide who the sender is.
+4. **Keep the link as short-lived as you can,** and close the popup when it is done.
+5. **Prefer a redirect-based sign-in flow** when your provider offers one, since it needs no opener at all.
+
+## User-Submitted Links
+
+If your site lets visitors post links, such as in comments or profiles, they are untrusted by definition. Make sure the link markup your code produces includes `rel="noopener noreferrer"` when it uses `target="_blank"`. Separately, the values `nofollow` and `ugc` tell search engines that the link was not editorially placed. They are about search, not security, so do not confuse them with `noopener`. Also check that only `http` and `https` addresses are allowed, as covered in [XSS Basics](./xss-basics).
+
+## Checking Your Setup
+
+1. In DevTools, open **Elements** and search for `target="_blank"`. Check each one has `rel="noopener"` or `rel="noreferrer"`.
+2. Search your JavaScript for `window.open(` and check each call passes `"noopener"` unless it truly needs the opener.
+3. Search for `rel="opener"`, and justify every match.
+4. Open a link in a new tab and type `window.opener` in the new tab's **Console**. It should be `null` for a protected link.
+5. Check the **Response Headers** of your page for `Cross-Origin-Opener-Policy`.
+6. Use the Link Scanner above on a few of your own links.
+
+## Best Practices
+
+1. **Add `rel="noopener"`** (or `noopener noreferrer`) to every `target="_blank"` link.
+2. **Pass `"noopener"` to `window.open`** unless you need the opener.
+3. **Do not use `rel="opener"`** without a clear reason.
+4. **Add the word even though modern browsers help,** for older browsers and clarity.
+5. **Scan user-generated links** and add protection automatically.
+6. **Use `postMessage` with an exact origin check** when a link back is needed.
+7. **Test login and payment popups** after any header change.
+8. **Warn visitors** when a link opens a new tab, for accessibility, as in [External Links](/tutorials/html/links-and-navigation/external-links).
+
+## Quick Checklist
+
+- [ ] Every `target="_blank"` link has `noopener` or `noreferrer`
+- [ ] `window.open` calls pass `"noopener"`
+- [ ] No `rel="opener"` without a comment explaining why
+- [ ] User-submitted links get protection added by your code
+- [ ] Any needed opener use relies on `postMessage` with origin checks
+- [ ] Sign-in and payment flows still work after header changes
+
+## Security and Privacy Notes
+
+- **The attack needs the visitor's trust in the old tab.** It depends on people returning to a tab they believe they know. A short, clear address and a habit of checking the address bar help visitors, but your code should not rely on that.
+- **Your own scripts can be the weak link.** A third-party script on your page can also call `window.open`. Review what you include, as covered in [Third-Party Content Security](/tutorials/html/embedded-content/third-party-content-security).
+- **`noopener` does not hide the referrer.** That is `noreferrer`. It also does not stop the new page from tracking the visitor through its own scripts.
+- **Test only your own pages,** or those you have permission to test.
+
+## Global Audience Notes
+
+- **Older browsers and embedded web views are still common in some regions,** and on older phones. Protection that does not depend on the browser default is safer.
+- **Many visitors use shared or family devices** and keep many tabs open for days, which is the situation the attack relies on.
+- **Say in the page's language** that a link opens a new tab, using visible text or an icon with an accessible name.
+
+## Common Mistakes to Avoid
+
+1. **Leaving `rel` off** because "browsers fix it now".
+2. **Forgetting `window.open`.**
+3. **Using `noreferrer` and assuming that is the only job of `noopener`,** or the reverse. The words are related but separate.
+4. **Writing `rel="noopener"` on a link with no `target`,** and thinking it does something.
+5. **Using `rel="opener"` for convenience.**
+6. **Treating a `null` return from `window.open("...", "_blank", "noopener")` as a bug.**
+7. **Letting `window.opener` decide trust** instead of checking `event.origin`.
+8. **Not protecting links that visitors post.**
+9. **Adding a strict `Cross-Origin-Opener-Policy` without testing** login popups.
+10. **Never re-checking** links after a redesign or a CMS change.
+
+## Practice Time
+
+1. In the Opener Lab, choose the "Older" browser with a plain link and nothing added, then press the run button. What does the original tab turn into?
+2. Choose `noopener`, and run it again. What changes?
+3. Switch to a modern browser with "nothing" selected for a link. Is the page protected? Now switch to `window.open()`. What happens?
+4. Choose `opener` for a link in a modern browser. What does it do?
+5. Tick "my own origin" with an unprotected link. How does the message differ?
+6. Paste your own links into the Link Scanner, and fix every problem it reports.
+7. Open any link with `target="_blank"` on a site you own, and check `window.opener` in the new tab's Console.
+8. Bonus: write a small function that adds `rel="noopener noreferrer"` to every outbound link in a block of user comments (using `textContent` for the text, as in [XSS Basics](./xss-basics)).
+
+## Quick Recap
+
+Click a question to check your answer.
+
+
+1. What is `window.opener`?
+
+A reference, available to a page opened by another page, that points back to the page that opened it.
+
+
+
+
+2. What is reverse tabnabbing?
+
+A new page you opened uses `window.opener.location` to turn your original tab into something else, such as a fake sign-in page, while the visitor is not looking.
+
+
+
+
+3. Can a cross-origin opened page read your page?
+
+No. But it can redirect your tab, send messages, and close or focus it. A same-origin page has full access.
+
+
+
+
+4. What does `rel="noopener"` do?
+
+It makes `window.opener` `null` in the new page, so it has no link back to yours.
+
+
+
+
+5. Do modern browsers make it unnecessary?
+
+Not entirely. They apply `noopener` to `target="_blank"` links, but not to `window.open()`, custom-named targets, or older browsers. Being explicit is still best.
+
+
+
+
+6. What if you really need the opener?
+
+Open only trusted pages, communicate with `postMessage`, check `event.origin` exactly, and close the popup when it is finished.
+
+
+
+## Key Takeaways
+
+- **`window.opener` is a link back to the page that opened a window.** Untrusted pages can use it to redirect your tab.
+- **`rel="noopener"` cuts the link.** `noreferrer` does that too, and also removes the referrer.
+- **Browsers help for `_blank` links,** but not for `window.open`, custom targets, or older browsers.
+- **`rel="opener"` and `Cross-Origin-Opener-Policy`** change this behaviour on purpose, so use them with care.
+- **When you need the link,** use `postMessage` with exact origin checks.
+- **Scan links regularly,** especially user-submitted ones.
+
+Next up: [Content Security Policy](./content-security-policy), where you will learn how a single header tells the browser which sources of scripts, styles, and frames to trust.
\ No newline at end of file
diff --git a/tutorials/html/16-security/noreferrer.mdx b/tutorials/html/16-security/noreferrer.mdx
new file mode 100644
index 000000000..195e6c948
--- /dev/null
+++ b/tutorials/html/16-security/noreferrer.mdx
@@ -0,0 +1,477 @@
+---
+id: html-sec-noreferrer
+title: "noreferrer and Referrer Policy"
+sidebar_label: "noreferrer"
+sidebar_position: 6
+slug: /html/security/noreferrer
+description: "Learn what the Referer header tells other sites, how rel=noreferrer, the referrerpolicy attribute, the meta tag and the Referrer-Policy header control it, and why secrets must never live in URLs. Includes a referrer lab and a policy picker."
+keywords:
+ - noreferrer
+ - rel noreferrer
+ - Referer header
+ - referrer policy
+ - referrerpolicy attribute
+ - Referrer-Policy header
+ - document.referrer
+ - strict-origin-when-cross-origin
+ - learn HTML
+ - CodeHarborHub HTML
+tags: [html, web-development, beginner, security, privacy, links, referrer, frontend]
+---
+
+import {useState} from 'react';
+
+export const policyList = [
+ "no-referrer",
+ "no-referrer-when-downgrade",
+ "origin",
+ "origin-when-cross-origin",
+ "same-origin",
+ "strict-origin",
+ "strict-origin-when-cross-origin",
+ "unsafe-url"
+];
+
+export function referrerSent(policy, from, to) {
+ let f;
+ let t;
+ try {
+ f = new URL(from);
+ t = new URL(to);
+ } catch (e) {
+ return null;
+ }
+ if ((f.protocol !== "https:" && f.protocol !== "http:") || (t.protocol !== "https:" && t.protocol !== "http:")) return null;
+ const full = f.origin + f.pathname + f.search;
+ const originOnly = f.origin + "/";
+ const same = f.origin === t.origin;
+ const down = f.protocol === "https:" && t.protocol === "http:";
+ switch (policy) {
+ case "no-referrer": return "";
+ case "no-referrer-when-downgrade": return down ? "" : full;
+ case "origin": return originOnly;
+ case "origin-when-cross-origin": return same ? full : originOnly;
+ case "same-origin": return same ? full : "";
+ case "strict-origin": return down ? "" : originOnly;
+ case "strict-origin-when-cross-origin": return same ? full : (down ? "" : originOnly);
+ case "unsafe-url": return full;
+ default: return null;
+ }
+}
+
+export function riskyParams(from) {
+ let u;
+ try {
+ u = new URL(from);
+ } catch (e) {
+ return [];
+ }
+ const names = [];
+ u.searchParams.forEach(function (value, name) {
+ if (/token|key|secret|session|password|reset|auth|code|email|otp/i.test(name)) names.push(name);
+ });
+ return names;
+}
+
+export function ReferrerLab() {
+ const [from, setFrom] = useState("https://shop.example.com/account/orders?id=4821&token=abc123#details");
+ const [to, setTo] = useState("https://analytics.example.net/collect");
+ const rows = policyList.map(function (p) { return {policy: p, sent: referrerSent(p, from, to)}; });
+ const invalid = rows[0].sent === null;
+ const risky = riskyParams(from);
+ return (
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {invalid ? (
+
Enter two full web addresses that start with http:// or https://.
+ This address contains {risky.join(", ")} in its query. Any policy that sends the full address would hand that value to the destination. Keep secrets out of URLs.
+
+ )}
+
+
+ The part after # is never sent. A simplified model of the rules in the Referrer Policy specification.
+
+
+ );
+}
+
+export const pickScenarios = [
+ {
+ title: "A password reset page. Its address holds a one-time code, and the page loads a logo and a link from other sites.",
+ ok: ["no-referrer", "same-origin"],
+ why: "Nothing from this address should reach other sites. The deeper fix is to avoid secrets in URLs, and the policy is a safety net."
+ },
+ {
+ title: "A blog that wants a privacy-friendly setting that still lets other sites see which site a visitor came from.",
+ ok: ["strict-origin-when-cross-origin"],
+ why: "Same-site requests get the full address, other https sites get only the origin, and nothing goes to an http site. It is also the usual browser default."
+ },
+ {
+ title: "A company intranet. Internal tools need the full address from each other, but nothing about internal pages may go outside.",
+ ok: ["same-origin"],
+ why: "same-origin sends the full address only to the same origin, and nothing anywhere else."
+ },
+ {
+ title: "A support page links to a sensitive external site. You want that site to learn nothing about where the visitor came from.",
+ ok: ["no-referrer"],
+ why: "no-referrer sends nothing. For a single link, rel=noreferrer does the same job."
+ }
+];
+
+export function PolicyPicker() {
+ const [idx, setIdx] = useState(0);
+ const [choice, setChoice] = useState("");
+ const [checked, setChecked] = useState(false);
+ const sc = pickScenarios[idx];
+ const good = sc.ok.indexOf(choice) !== -1;
+ return (
+
+
Scenario {idx + 1} of {pickScenarios.length}: {sc.title}
+
+
+
+
+
+
+ {checked && (
+
+ {good ? "Correct. " : "Not quite. "}
+ {good ? "" : "A good answer here: " + sc.ok.join(" or ") + ". "}
+ {sc.why}
+
0 ? "#c0392b" : "inherit", fontWeight: naiveFlags.length > 0 ? 600 : 400}}>
+ {c.id === "js" ? "Quotes or brackets in the text can break the script, or let the visitor write code in it." : (naiveFlags.length > 0 ? "Risky: " + naiveFlags.join("; ") + "." : "Nothing risky built from this text.")}
+
+
With the right encoding:
+
{safe}
+
+ {c.id === "js" ? "The text stays a string, and cannot close the script early." : (safeFlags.length > 0 ? "Still risky: " + safeFlags.join("; ") + "." : "Nothing risky. The text stays data.")}
+
+ This lab never inserts your text into the page. It builds the markup as text and uses an inert parser, which runs no code, to list what would be created.
+
+
+ );
+}
+
+export function ContextLab() {
+ return (
+ Loading the lab...}>
+ {function () { return ; }}
+
+ );
+}
+
+export const sinkItems = [
+ {
+ code: 'el.textContent = comment;',
+ answer: "safe",
+ why: "textContent treats the value as plain text. Nothing is parsed as markup."
+ },
+ {
+ code: 'el.innerHTML = comment;',
+ answer: "unsafe",
+ why: "innerHTML parses the value as HTML. If the comment came from a visitor, it can create elements and handlers."
+ },
+ {
+ code: 'list.insertAdjacentHTML("beforeend", "
" + name + "
");',
+ answer: "unsafe",
+ why: "Building markup from strings that include visitor text is the classic cause of XSS. Create the element and set its textContent instead."
+ },
+ {
+ code: 'const li = document.createElement("li");\nli.textContent = name;\nlist.append(li);',
+ answer: "safe",
+ why: "The element is created by code, and the name is set as text. This is the pattern to prefer."
+ },
+ {
+ code: 'link.href = userUrl;',
+ answer: "unsafe",
+ why: "A javascript: address would be accepted. Check the scheme against an allow-list (http, https, mailto) first."
+ },
+ {
+ code: 'el.innerHTML = DOMPurify.sanitize(comment);',
+ answer: "safe",
+ why: "A well-maintained sanitising library, kept up to date and configured with an allow-list, is the right tool when you must allow some HTML. It is safe only as long as the library is current."
+ },
+ {
+ code: 'document.write(location.search);',
+ answer: "unsafe",
+ why: "The address bar can be written by anyone who links to your page, and document.write parses it as HTML. Avoid document.write."
+ },
+ {
+ code: 'img.alt = description;',
+ answer: "safe",
+ why: "Setting a plain property such as alt treats the value as text, and it cannot create elements or run code."
+ },
+ {
+ code: 'eval(userInput);',
+ answer: "unsafe",
+ why: "eval runs text as code. Never pass it anything a visitor can influence. There is almost always a safer way."
+ }
+];
+
+export function SinkQuiz() {
+ const [picked, setPicked] = useState({});
+ const done = Object.keys(picked).length;
+ const correct = sinkItems.filter(function (s, i) { return picked[i] === s.answer; }).length;
+ return (
+
+
+ Answered {done} of {sinkItems.length}. Correct: {correct}.
+
+
Each line handles text that a visitor wrote. Is it safe?
+ );
+}
+
+# XSS Basics: Cross-Site Scripting
+
+Imagine a guestbook page. A visitor types a message, and your page shows it to everyone. Now imagine the "message" is not words but a piece of code, and your page treats it as part of its own HTML. Every visitor who opens the guestbook now runs that code, with all the power of your site. That is **cross-site scripting**, or **XSS**, and it is one of the most common and most damaging web page problems.
+
+The good news is that the cause is simple and the cure is well understood: keep **data** and **code** apart. This lesson shows you how.
+
+## What You Will Learn
+
+- What XSS is, and what an attacker can do with it
+- The three types: stored, reflected, and DOM-based
+- Why it happens, in one sentence
+- How to escape output correctly for each context
+- Which DOM methods are safe, and which are not
+- How to handle links and addresses supplied by visitors
+- What to do when you must allow some HTML
+- Which extra layers reduce the damage if something slips through
+
+
+
+
+## The Big Idea
+
+XSS happens when **untrusted text is turned into markup or code.** The fix is to make sure untrusted text always stays text.
+
+
+
+
+```js title="unsafe.js"
+// UNSAFE: the comment is parsed as HTML
+const out = document.querySelector("#comment");
+out.innerHTML = comment;
+```
+
+```js title="safe.js"
+// SAFE: the comment is only ever text
+const out = document.querySelector("#comment");
+out.textContent = comment;
+```
+
+```js title="safe-list.js"
+// SAFE: build elements with code, and set text on them
+const li = document.createElement("li");
+li.textContent = name;
+list.append(li);
+```
+
+
+
+
+
+<>
+
+>
+
+
+
+
+
+
+<>
+
+>
+
+
+
+
+
+In the Context Lab, press the "Attribute breakout" and "Tag injection" presets. Look at how the same text is risky in one context and harmless once encoded, and how each context needs its own kind of encoding.
+
+## What an Attacker Can Do
+
+Injected code runs **as your page**, with your origin's full power ([HTML Security Basics](./html-security-basics) explains why). Depending on the site, that can mean:
+
+- Reading anything the page can read, including personal information on screen
+- Acting as the visitor, for example sending requests, changing settings, or posting messages
+- Changing what the page shows, for example adding a fake login form
+- Capturing what the visitor types
+- Reading cookies and storage that script can access, which is why sensitive cookies should be marked `HttpOnly`
+- Redirecting the visitor to another site
+
+You do not need to know how attacks are written to defend against them. You need to know that **any path that lets untrusted text become code is a vulnerability**, and to close those paths.
+
+## The Three Types
+
+| Type | How the text gets in | Where it is injected | Example |
+| :-- | :-- | :-- | :-- |
+| **Stored** | A visitor saves it (a comment, a profile) | Your server later sends it to other visitors | A malicious comment shown to everyone |
+| **Reflected** | It is in a link or request, such as a search term in the address | Your server echoes it straight back in the response | A crafted link that shows an unescaped search term |
+| **DOM-based** | It is in the address, or another browser-side source | Your own script inserts it into the page, with no server involved | A script that reads the address fragment and writes it with `innerHTML` |
+
+The cure is the same for all three: escape on output, and use safe methods. What changes is **where** you apply it: in the server's templates, or in your browser-side code.
+
+## Why It Happens
+
+Browsers cannot tell the difference between markup **you** wrote and markup that **a visitor** wrote, once they are mixed into the same string. If you build HTML by joining strings, the browser parses the result as one document, and everything in it is trusted.
+
+```js
+const html = "
Hello, " + name + "
"; // name is now part of the markup
+```
+
+If `name` contains something that looks like a tag, the parser creates a tag. The rule that prevents this is simple: **never build markup out of untrusted strings.** Build it with safe APIs, or escape the strings first.
+
+## Escape for the Context
+
+Escaping means replacing characters that have a special meaning with harmless ones. The right replacement depends on **where** the text is going, because each place has its own special characters:
+
+| Context | Example | What to do |
+| :-- | :-- | :-- |
+| HTML text | `
+ {r.added.length === 0 ? "The parser added no structural elements." : "Added by the parser, not by you: " + r.added.join(", ")}
+
+
+ This uses the browser's own HTML parser to build a separate, inert document. Nothing you type is put into this page as HTML, and no script in it would run. The shape of the result is the same in every modern browser, because the standard defines it step by step.
+
", valid: true, why: "A ul may contain li elements (and script-supporting elements such as script and template)."},
+ {code: "
One
", valid: false, why: "A ul may not have a div as a direct child. Put the div inside an li."},
+ {code: "
Hello world
", valid: true, why: "A p holds phrasing content, and strong is phrasing content."},
+ {code: "
Intro
A box
", valid: false, why: "A p may hold only phrasing content, and div is not. The parser even closes the p before the div, as the Parser Lab shows."},
+ {code: "
", valid: true, why: "The a element is transparent: it may hold whatever its parent may hold. A div is fine where the parent allows flow content."},
+ {code: "", valid: false, why: "A button may not contain interactive content, and a link is interactive."},
+ {code: "
Text
Title", valid: false, why: "The content model is one summary element, first, followed by flow content."},
+ {code: "
Cell
", valid: true, why: "The model allows tr elements directly in a table. Browsers will still add a tbody to the page they build."},
+ {code: "
Cell
", valid: false, why: "A td must sit inside a tr. Without one, the markup is not valid."}
+];
+
+export function ModelQuiz() {
+ const [answers, setAnswers] = useState({});
+ const answered = Object.keys(answers).length;
+ const correct = modelItems.filter(function (it, i) { return answers[i] === (it.valid ? "valid" : "invalid"); }).length;
+ const set = function (i, v) {
+ setAnswers(function (prev) { const n = Object.assign({}, prev); n[i] = v; return n; });
+ };
+ return (
+
+
Is each snippet valid HTML according to the content model of its elements?
+ {modelItems.map(function (it, i) {
+ const a = answers[i];
+ const right = a === (it.valid ? "valid" : "invalid");
+ return (
+
+ );
+}
+
+# The HTML Living Standard
+
+Every element you have used in this course, from `p` to `form`, is defined in one place: a long, carefully written document called the **HTML Standard**. It decides what each element means, what it may contain, and exactly how a browser must read your markup. Knowing a little about this document makes you a calmer, more confident developer, because "how does HTML work?" has a real, public answer.
+
+## What You Will Learn
+
+- A short history of HTML, and why "HTML5" is not the end of the story
+- Who maintains the standard, and what "living" means
+- How a new feature gets into HTML
+- How the parser handles broken markup the same way in every browser
+- How to read an element's entry in the specification
+- How the standard, MDN, and validators fit together
+
+
+
+
+## The Big Idea
+
+HTML used to be released in numbered versions. Today there is **one standard that is edited continuously**, and browsers follow it. You do not "upgrade to a new HTML". You learn new features as browsers support them, on top of everything that still works.
+
+
+
+
+
+<>
+
+>
+
+
+
+
+
+
+<>
+
+>
+
+
+
+
+
+```html title="index.html"
+
+
+
+
+
+
+
+
Valid
+
+
+
+
First
+
Second
+```
+
+
+
+
+## A Short History
+
+| When | What happened |
+| :-- | :-- |
+| Early 1990s | Tim Berners-Lee describes the first version of HTML for the early web |
+| 1995 | **HTML 2.0** is published by the IETF, the first formal standard |
+| 1997 | **HTML 3.2** from the W3C. **HTML 4.01** follows in 1999 |
+| 2000 | **XHTML 1.0**, a stricter, XML-based version of HTML, is published |
+| 2004 | Browser makers (Apple, Mozilla, and Opera) form the **WHATWG**, because they want HTML to grow to fit real web applications |
+| Around 2011 | The WHATWG drops the "5" and calls its document the **HTML Living Standard** |
+| 2014 | The W3C publishes **HTML5** as a finished recommendation |
+| 2019 | The W3C and WHATWG agree that the WHATWG's living standard is the single, official HTML specification |
+
+So "HTML5" was a real milestone, and it is still a handy word for "modern HTML". But there is **no HTML6 planned**. The standard keeps changing in small steps.
+
+:::info
+The WHATWG is a community of browser makers and others. Its steering group includes Apple, Google, Mozilla, and Microsoft. Anyone can suggest a change in the open, on the project's public GitHub repository.
+:::
+
+## What "Living" Means for You
+
+- **No version numbers to wait for.** New features appear in the standard, then in browsers, one at a time.
+- **Backward compatibility is a rule.** Browsers keep supporting old pages. A page written long ago still works, so your skills do not expire.
+- **Support differs by browser and version.** A feature can be in the standard and still be missing in some browsers. That is why you check support, as the [Modern HTML overview](/tutorials/html/modern-html) explains.
+- **The document changes.** When you read a tutorial, an article, or this one, ask how old it is.
+
+## How a Feature Gets Into HTML
+
+The exact process has details, but the broad path is:
+
+1. **A problem is noticed.** For example, "everyone builds pop-ups from scratch, and gets focus wrong".
+2. **An idea is discussed in public,** often in an incubation group or on GitHub, with browser makers, developers, and accessibility experts.
+3. **A specification is written.** It says exactly how the feature must behave, including edge cases and errors.
+4. **Tests are written.** A shared test suite called web-platform-tests checks that every browser behaves the same way.
+5. **Browsers implement it.** Usually the standard needs more than one browser engine to be interested before a change is accepted.
+6. **Documentation is written,** for example on MDN, and the feature gets a Baseline label as support grows.
+7. **Developers use it,** with fallbacks while support is still spreading.
+
+That is why features such as `dialog` and the `popover` attribute took time to be ready: each step needs several groups to agree.
+
+## What Is in the Standard
+
+The HTML Standard is much more than a list of tags. It also defines:
+
+- **Every element,** with its meaning, where it may appear, what it may contain, and its attributes.
+- **How browsers parse HTML,** step by step, including what to do with mistakes.
+- **Web APIs that belong to HTML,** such as `postMessage`, web storage, web workers, the history API, and drag and drop.
+- **Rules for forms, media, canvas, and embedding,** and for how pages load.
+
+It does not define everything on a web page. Other standards cover the rest:
+
+| Topic | Who defines it |
+| :-- | :-- |
+| HTML elements, parsing, and many web APIs | WHATWG HTML Standard |
+| The DOM, URLs, and network requests (`fetch`) | Other WHATWG standards |
+| CSS | The W3C CSS Working Group |
+| JavaScript | Ecma International, TC39 (ECMAScript) |
+| Accessibility roles and attributes (ARIA) | The W3C |
+
+## The Parser: Forgiving, but Exactly Defined
+
+When you forget a closing tag, the browser does not show an error. It repairs the markup. In older days, every browser repaired it a little differently, which was a big source of bugs. The modern standard defines the **repair rules precisely**, so every browser builds the same page from the same markup.
+
+Open the **Parser Lab** tab and try the buttons:
+
+- **Unclosed paragraphs:** the second `p` closes the first.
+- **Table without `tbody`:** the parser adds a `tbody` for you.
+- **Crossed tags:** the parser rearranges `b` and `i` so the page still has a valid tree.
+- **A div inside a p:** a `p` cannot hold a `div`, so the parser closes the `p` first.
+- **Bare text:** the parser adds `html`, `head`, and `body`.
+
+The lab tells you which structural elements the parser added. This is why a page can look right in a browser and still be invalid HTML, and why it is worth validating your markup.
+
+:::warning
+The parser's repairs are about **safety nets**, not about being sloppy on purpose. Do not rely on repairs. Write correct markup, and check the result in DevTools. Differences between how a **sanitiser** and a **browser** parse markup have caused real security bugs, so never write your own HTML cleaner with regular expressions. Use the browser's parser, or a maintained library, as covered in [XSS Basics](/tutorials/html/security/xss-basics).
+:::
+
+## Reading an Element's Entry in the Standard
+
+You do not need to read the standard from start to finish. But once you know its layout, you can look up any element in a few seconds. Each element's entry has the same parts:
+
+| Part | What it tells you |
+| :-- | :-- |
+| **Categories** | Groups the element belongs to, such as flow content, phrasing content, or interactive content |
+| **Contexts in which this element can be used** | Where the element may appear |
+| **Content model** | What the element may contain |
+| **Content attributes** | The attributes it supports |
+| **Accessibility considerations** | Notes on roles and use by assistive technology |
+| **DOM interface** | The JavaScript object and its properties and methods |
+
+The **content model** is the part that settles most arguments. Open the **Content Model Quiz** tab, and decide whether each snippet is valid. Then, on the specification's page for each element, read its content model line to confirm your answer.
+
+### Words you will meet
+
+- **Flow content:** most elements that can appear in the body, such as `p`, `div`, and `section`.
+- **Phrasing content:** the text and inline elements inside a paragraph, such as `strong`, `a`, and `span`.
+- **Interactive content:** elements a visitor can interact with, such as `a`, `button`, and `input`.
+- **Transparent:** the element takes whatever its parent allows, as `a` does.
+
+## The Standard, MDN, and Validators
+
+| Tool | Best for |
+| :-- | :-- |
+| **The HTML Standard** (html.spec.whatwg.org) | The final answer on exact behaviour. Precise, but written for implementers |
+| **MDN Web Docs** | Friendly explanations, examples, and browser support tables |
+| **A validator**, such as the Nu Html Checker | Checking your own pages against the standard's rules |
+| **DevTools** | Seeing the page the browser actually built |
+
+A good habit: use MDN to learn, the standard to settle a disagreement, and a validator to check your work.
+
+## Obsolete Features
+
+Some features from the past, such as `font`, `center`, `marquee`, and presentational attributes like `align`, are **obsolete**. The standard says authors must not use them, but browsers still have to support them so old pages do not break. For new pages, use the modern replacement: CSS for looks, and meaningful elements for structure.
+
+## Checking Your Setup
+
+1. Run your page through the **Nu Html Checker** (the validator at validator.w3.org/nu), and read the messages. Each cites a rule from the standard.
+2. Compare **View Source** with the **Elements** panel in DevTools. Elements shows the page the parser built, with repairs applied.
+3. For any element you are unsure about, read its **content model** in the specification.
+4. Check the date on any tutorial. If it is old, confirm the details on MDN.
+5. For a new feature, check the **Baseline** label and the compatibility table on MDN.
+
+## Best Practices
+
+1. **Write valid markup,** and let the parser's repairs be a safety net only.
+2. **Validate your pages** now and then, especially after big changes.
+3. **Use the standard to settle questions,** and MDN to learn.
+4. **Check support** before using a new feature.
+5. **Prefer current elements and CSS** over obsolete ones.
+6. **Keep the doctype** `` at the top of every page.
+7. **Check old advice** against current sources.
+8. **Do not write your own HTML sanitiser.**
+
+## Quick Checklist
+
+- [ ] My pages begin with ``
+- [ ] My markup passes the validator, or I understand each message
+- [ ] I check content models for elements I am unsure about
+- [ ] I compare View Source with the Elements panel when something looks odd
+- [ ] I check browser support before using a new feature
+- [ ] I use no obsolete elements or attributes in new work
+
+## Security and Privacy Notes
+
+- **Parsing differences can be exploited.** Attackers sometimes rely on markup that two parsers read differently. Always sanitise with the same kind of parser the browser uses, or a maintained library. See [XSS Basics](/tutorials/html/security/xss-basics).
+- **Do not paste private markup into online tools.** A validator or playground that is a website receives what you send. Use made-up examples, or run a checker locally.
+- **A forgiving parser is not a safe parser.** Repairs help layout, not security.
+
+## Global Audience Notes
+
+- **The standard is written in English,** and most translations lag behind it. MDN has many translations, but they can be out of date, so check the date.
+- **Languages and scripts are part of HTML.** Attributes like `lang` and `dir`, covered in earlier lessons, are in the standard, and matter for screen readers, fonts, and right-to-left text.
+- **Older browsers and devices exist everywhere.** A living standard means different visitors have different features, so build a solid base.
+
+## Common Mistakes to Avoid
+
+1. **Treating "HTML5" as the latest version,** and waiting for HTML6.
+2. **Relying on the parser's repairs** instead of writing valid markup.
+3. **Trusting an old tutorial** without checking MDN.
+4. **Confusing View Source** with what the browser actually built.
+5. **Using obsolete elements** because they still work.
+6. **Skipping the doctype.**
+7. **Assuming a feature in the standard works everywhere.**
+8. **Writing a regular expression to clean HTML.**
+9. **Ignoring validator messages,** instead of reading the rule behind them.
+10. **Mixing up the standards,** and looking for CSS rules in the HTML Standard.
+
+## Practice Time
+
+1. In the Parser Lab, click each sample button. Which ones make the parser add elements? Which structural elements does it add?
+2. Type a paragraph with no closing tag followed by a `ul`. What does the parser do?
+3. Type `
One
Two
`. Where does the page end the `p`?
+4. Complete the Content Model Quiz. Which answer surprised you?
+5. Open the Nu Html Checker, and paste a small page of your own (without anything private). Read the first three messages.
+6. Compare View Source and the Elements panel on a page with a table. What differs?
+7. Look up the content model of `button` on MDN or in the standard. Write it in your own words.
+8. Bonus: find the oldest tutorial you can on a topic, and list what is out of date.
+
+## Quick Recap
+
+Click a question to check your answer.
+
+
+1. What is the HTML Living Standard?
+
+The single, continuously updated specification of HTML, maintained by the WHATWG with browser makers. It replaces numbered versions.
+
+
+
+
+2. Will there be an HTML6?
+
+No version is planned. HTML changes in small steps instead, and features arrive in browsers one at a time.
+
+
+
+
+3. How does a feature get into HTML?
+
+It is proposed and discussed in public, specified in detail, tested with shared tests, implemented by browsers, and then documented. A change normally needs interest from more than one browser engine.
+
+
+
+
+4. Why does broken markup look the same in every browser?
+
+The standard defines the parser's repair rules step by step, so every browser builds the same page from the same input.
+
+
+
+
+5. What is a content model?
+
+The rule that says what an element may contain. It settles whether a snippet is valid, such as whether a `p` may hold a `div`.
+
+
+
+
+6. When do you use MDN, the standard, and a validator?
+
+MDN to learn and check support, the standard to settle exact behaviour, and a validator to check your own pages.
+
+
+
+## Key Takeaways
+
+- **HTML is one living standard,** edited continuously by the WHATWG with browser makers.
+- **There are no new numbered versions.** Features arrive and spread over time.
+- **The parser is forgiving and exactly defined.** Still, write valid markup.
+- **Content models explain** what each element may contain.
+- **MDN teaches, the standard decides, validators check.**
+- **Old features still work, but avoid them** in new pages.
+- **Never rely on your own regular expressions** to clean HTML.
+
+Next up: [Modern HTML Features](./modern-html-features), where you will take a guided tour of newer attributes and elements, and learn to judge which ones are ready for your site.
\ No newline at end of file
diff --git a/tutorials/html/17-modern-html/index.mdx b/tutorials/html/17-modern-html/index.mdx
index 7a1cd5c46..da01df8ec 100644
--- a/tutorials/html/17-modern-html/index.mdx
+++ b/tutorials/html/17-modern-html/index.mdx
@@ -1,14 +1,413 @@
+---
+id: modern-html-overview
+title: "Modern HTML: Built-In Features for Today's Web"
+sidebar_label: "Modern HTML"
+sidebar_position: 1
+slug: /html/modern-html
+description: "Start learning modern HTML: how the HTML Living Standard works, how to tell which new features are safe to use, and how dialog, details, popover, template, slot, inert, lazy loading and web components replace code you used to write yourself. Includes a live browser feature check and an old-way-or-new-way matcher."
+keywords:
+ - modern HTML
+ - HTML living standard
+ - HTML dialog popover
+ - HTML template slot
+ - inert attribute
+ - web components
+ - progressive enhancement
+ - feature detection
+ - Baseline browser support
+ - learn HTML
+ - CodeHarborHub HTML
+tags: [html, web-development, beginner, modern-html, dialog, popover, web-components, progressive-enhancement, frontend]
+---
+
+import {useState} from 'react';
+import BrowserOnly from '@docusaurus/BrowserOnly';
+import Link from '@docusaurus/Link';
+
+export const featureTests = [
+ {id: "dialog", label: "The dialog element (showModal)", lesson: "Dialog", href: "/html/modern-html/dialog", code: "typeof HTMLDialogElement === 'function'",
+ test: function () { return typeof HTMLDialogElement === "function" && typeof HTMLDialogElement.prototype.showModal === "function"; }},
+ {id: "details", label: "Exclusive details groups (the name attribute)", lesson: "Details and Summary", href: "/html/modern-html/details-summary", code: "'name' in document.createElement('details')",
+ test: function () { return "name" in document.createElement("details"); }},
+ {id: "popover", label: "The popover attribute", lesson: "Popover", href: "/html/modern-html/popover", code: "'popover' in HTMLElement.prototype",
+ test: function () { return "popover" in HTMLElement.prototype; }},
+ {id: "inert", label: "The inert attribute", lesson: "inert", href: "/html/modern-html/inert", code: "'inert' in HTMLElement.prototype",
+ test: function () { return "inert" in HTMLElement.prototype; }},
+ {id: "template", label: "The template element", lesson: "template", href: "/html/modern-html/template", code: "'content' in document.createElement('template')",
+ test: function () { return "content" in document.createElement("template"); }},
+ {id: "slot", label: "The slot element", lesson: "slot", href: "/html/modern-html/slot", code: "typeof HTMLSlotElement === 'function'",
+ test: function () { return typeof HTMLSlotElement === "function"; }},
+ {id: "custom", label: "Custom elements", lesson: "Web Components in HTML", href: "/html/modern-html/web-components-html", code: "typeof customElements.define === 'function'",
+ test: function () { return "customElements" in window && typeof window.customElements.define === "function"; }},
+ {id: "shadow", label: "Shadow DOM", lesson: "Web Components in HTML", href: "/html/modern-html/web-components-html", code: "typeof Element.prototype.attachShadow === 'function'",
+ test: function () { return typeof Element.prototype.attachShadow === "function"; }},
+ {id: "lazyimg", label: "Native lazy loading for images", lesson: "Lazy Loading", href: "/html/modern-html/lazy-loading", code: "'loading' in HTMLImageElement.prototype",
+ test: function () { return "loading" in HTMLImageElement.prototype; }},
+ {id: "lazyframe", label: "Native lazy loading for iframes", lesson: "Lazy Loading", href: "/html/modern-html/lazy-loading", code: "'loading' in HTMLIFrameElement.prototype",
+ test: function () { return "loading" in HTMLIFrameElement.prototype; }}
+];
+
+export function runFeatureTests() {
+ return featureTests.map(function (f) {
+ let ok = false;
+ try {
+ ok = Boolean(f.test());
+ } catch (e) {
+ ok = false;
+ }
+ return {id: f.id, label: f.label, lesson: f.lesson, href: f.href, code: f.code, ok: ok};
+ });
+}
+
+export function FeatureCheckInner() {
+ const [results, setResults] = useState(function () { return runFeatureTests(); });
+ const count = results.filter(function (r) { return r.ok; }).length;
+ return (
+
+
+ These are real checks, run by your browser right now. Each one is the kind of test you can put in your own code.
+
+
+
+
+
Feature
+
Supported here?
+
The check
+
+
+
+ {results.map(function (r) {
+ return (
+
+
{r.label} Lesson: {r.lesson}
+
{r.ok ? "Yes" : "No"}
+
{r.code}
+
+ );
+ })}
+
+
+
Your browser supports {count} of {results.length} of these features.
+
+
+ Nothing is sent anywhere. Having a property does not prove every detail works, so treat a check as a first test and read the lesson for the details. Visitors with older browsers will see "No" for some rows, and your page should still work for them.
+
+
+ );
+}
+
+export function FeatureCheck() {
+ return (
+ Checking your browser...}>
+ {function () { return ; }}
+
+ );
+}
+
+export const modernOptions = [
+ "dialog", "details and summary", "popover", "template", "slot", "inert", "loading=\"lazy\"", "custom elements and shadow DOM"
+];
+
+export const modernItems = [
+ {job: "A pop-up window built from a div, a dark overlay, and your own code to trap the keyboard focus", answer: "dialog"},
+ {job: "A show-and-hide section driven by a click handler that toggles a class", answer: "details and summary"},
+ {job: "A tooltip or menu that you open with a script and close when the visitor clicks elsewhere", answer: "popover"},
+ {job: "A block of markup you copy many times by gluing together strings and setting innerHTML", answer: "template"},
+ {job: "Letting the page author put their own content inside named places in a component", answer: "slot"},
+ {job: "Making everything behind an open panel unreachable by keyboard and screen reader", answer: "inert"},
+ {job: "A scroll listener that swaps in image addresses as pictures come near the screen", answer: "loading=\"lazy\""},
+ {job: "A reusable user-card tag with its own markup and styles that the rest of the page cannot disturb", answer: "custom elements and shadow DOM"}
+];
+
+export function ModernMatcher() {
+ const [picked, setPicked] = useState({});
+ const [checked, setChecked] = useState(false);
+ const correct = modernItems.filter(function (it, i) { return picked[i] === it.answer; }).length;
+ return (
+
+
For each job people used to code by hand, pick the built-in feature that now helps.
+ );
+}
+
+Ten years ago, a pop-up window, a tooltip, or a reusable widget meant a JavaScript library, a pile of extra code, and a lot of accessibility bugs. Today HTML itself can do much of this work. The browser handles focus, the Escape key, layering, and screen reader announcements, and you write a few lines of markup.
+
+This section shows you those features: what each one does, how to use it safely, and what to do for visitors whose browsers do not have it yet.
+
+## What You Will Learn
+
+- Why HTML is now a "living standard", and what that means for you
+- How to tell whether a new feature is safe to use
+- What `dialog`, `details`, `popover`, `inert`, `template`, `slot`, native lazy loading, and web components are for
+- How to build on a solid base and add modern features on top
+- How to check support in your own code
+
+
+
+
+## The Big Idea
+
+A rule of thumb for the modern web: **if HTML or CSS can do it, let them.** Built-in features are usually shorter, faster, and more accessible than a hand-written version. They are also tested by browser makers, on more devices than you will ever own.
+
+
+
+
+```html title="index.html"
+
+
+
+
+
+
+ Delivery information
+
Orders ship within two working days.
+
+
+
+
+
Press Escape to close this.
+
+
```
- ├── 17-modern-html/
- │ ├── index.mdx
- │ ├── html-living-standard.mdx
- │ ├── modern-html-features.mdx
- │ ├── dialog.mdx
- │ ├── details-summary.mdx
- │ ├── popover.mdx
- │ ├── template.mdx
- │ ├── slot.mdx
- │ ├── inert.mdx
- │ ├── lazy-loading.mdx
- │ └── web-components-html.mdx
-```
\ No newline at end of file
+
+
+
+
+
+<>
+
+>
+
+
+
+
+
+
+<>
+
+>
+
+
+
+
+
+## HTML Is a Living Standard
+
+You may have heard of HTML5. It was a big milestone, around 2014, but it was not the end of the story. Today, HTML is maintained as a **living standard** by an open group called the WHATWG, together with browser makers. There is no "HTML6" to wait for. Instead, the specification changes continuously, small features are added, and browsers ship them one by one.
+
+That changes how you work:
+
+- **Features arrive at different times in different browsers.** A feature can work in one browser this year and in another next year.
+- **"What version of HTML?" is the wrong question.** The right one is "do my visitors' browsers support this feature?"
+- **Learning never finishes,** but the base is stable. Elements you learned years ago still work.
+
+The next lesson, [The HTML Living Standard](./modern-html/html-living-standard), explains how this works in practice and where to read the real specification.
+
+## Can I Use This Feature?
+
+Before you rely on any new feature, check support. A few reliable places are:
+
+- **MDN Web Docs.** Each page has a browser compatibility table at the bottom.
+- **Baseline.** A shared label from browser makers that tells you how widely a feature works. **Newly available** means it works in the latest versions of all the major browsers. **Widely available** means it has worked in all of them for at least about two and a half years, so it is safe for most sites.
+- **Can I use.** A site that shows support by browser version and usage share.
+
+Then decide what fits **your** visitors. A site for a tech-savvy audience on current phones can use newer features sooner. A site for people on older, shared, or low-cost devices should wait for wider support, or provide a fallback.
+
+## From Old Way to Modern Way
+
+| The job | The old way | The modern way | Lesson |
+| :-- | :-- | :-- | :-- |
+| A modal pop-up | A `div`, an overlay, a focus trap, many bugs | `dialog` with `showModal()` | [Dialog](./modern-html/dialog) |
+| A show and hide section | A click handler and a class | `details` and `summary` | [Details and Summary](./modern-html/details-summary) |
+| A tooltip, menu, or card that opens on demand | A script, positioning code, click-outside handling | The `popover` attribute | [Popover](./modern-html/popover) |
+| A block of markup used many times | Strings and `innerHTML` | `template` | [template](./modern-html/template) |
+| Content placed inside a component | Custom code to move nodes around | `slot` | [slot](./modern-html/slot) |
+| Blocking the background while a panel is open | Many `tabindex` and `aria-hidden` changes | The `inert` attribute | [inert](./modern-html/inert) |
+| Loading images and frames late | Scroll listeners and observers | `loading="lazy"` | [Lazy Loading](./modern-html/lazy-loading) |
+| A reusable custom tag | A framework, or copying and pasting | Custom elements and shadow DOM | [Web Components in HTML](./modern-html/web-components-html) |
+
+Open the **Old Way or New Way?** tab and test yourself on this table.
+
+## What Is in This Section
+
+
+
+## Progressive Enhancement
+
+The most useful habit for modern HTML is **progressive enhancement**: build a page that works with plain, widely supported HTML, then add newer features on top. If a feature is missing, the visitor gets the simple version, not a broken page.
+
+A good example is `details`, which works as a heading and its content even if nothing else is available. Another is a link that goes to a full page, which a script upgrades into a pop-up when `dialog` is supported.
+
+```html
+
+Settings
+```
+
+```js
+// Enhance it only where dialog is supported
+const link = document.getElementById("settings-link");
+if (typeof HTMLDialogElement === "function") {
+ link.addEventListener("click", function (event) {
+ event.preventDefault();
+ // open a dialog with the settings form here
+ });
+}
+```
+
+### Detecting features
+
+Check for the **feature**, not for the browser name. Browser names change, and visitors can disguise them. These are typical checks:
+
+```js
+// Is the dialog element available?
+const hasDialog = typeof HTMLDialogElement === "function";
+
+// Is the popover attribute available?
+const hasPopover = "popover" in HTMLElement.prototype;
+
+// Does CSS understand a selector?
+const hasPopoverOpen = CSS.supports("selector(:popover-open)");
+```
+
+The **What Can Your Browser Do?** tab above runs checks like these in your own browser. Compare the results with a friend's phone or an older device, if you can.
+
+## Using New Features Safely
+
+1. **Check support,** on MDN or Baseline, and note the fallbacks.
+2. **Start with a working base.** Plain HTML first, features second.
+3. **Test in more than one browser,** and on a real phone, if you can.
+4. **Use a polyfill only when you need it.** A polyfill is a script that adds a missing feature. It adds weight, so weigh the cost.
+5. **Check accessibility.** Test with the keyboard alone, and with a screen reader if you can.
+6. **Re-check from time to time.** A feature that was not ready last year may be today.
+
+## Modern Does Not Mean Safe
+
+Built-in features save work, but they do **not** remove the need for the habits in the [HTML Security](/tutorials/html/security) section:
+
+- `template` and web components still need escaping when you put visitor text inside them. See [XSS Basics](/tutorials/html/security/xss-basics).
+- A `dialog` or `popover` is not a security boundary. It only changes what is shown.
+- Shadow DOM is an organising tool, not a way to hide anything from scripts or attackers.
+- A new feature can have its own pitfalls, so read each lesson's security notes.
+
+## Accessibility at a Glance
+
+Built-in features come with **keyboard and screen reader behaviour** that you would otherwise have to rebuild:
+
+- `dialog` moves focus into the dialog, keeps it there when opened with `showModal()`, and closes with Escape.
+- `details` and `summary` can be opened with the keyboard, and announce their state.
+- `popover` handles light dismiss and the Escape key, and `inert` keeps hidden areas out of reach.
+
+Your job is to use them as intended: add a heading and a way to close, write clear labels, and test with the keyboard. The existing lessons on [Dialog](/tutorials/html/semantic-html/dialog) and [Details](/tutorials/html/semantic-html/details) in the Semantic HTML section introduce those elements. The lessons here go further, with a modern focus and different examples.
+
+## Global Audience Notes
+
+- **Browser versions vary.** Many visitors use older phones, shared computers, or devices that no longer get updates. Fallbacks protect them.
+- **Data costs matter.** A native feature usually costs fewer bytes than a library that does the same job.
+- **Languages and writing directions differ.** Test dialogs, popovers, and components with long words and right-to-left text, and avoid fixed widths.
+- **Cultures differ in expectations.** For example, a pop-up that blocks the page may be more irritating in some places than others. Use dialogs sparingly, and never trap people.
+
+## Common Mistakes to Avoid
+
+1. **Using a new feature without checking support.**
+2. **Replacing a working base** with a feature-only version, so older browsers see nothing.
+3. **Detecting the browser name** instead of the feature.
+4. **Adding a polyfill by habit,** and paying for code you do not need.
+5. **Rebuilding by hand** something HTML already does.
+6. **Skipping the keyboard test.**
+7. **Treating `dialog`, `popover`, or shadow DOM as security.**
+8. **Not re-checking support** as browsers improve.
+9. **Copying code** that mixes old and new patterns without understanding it.
+10. **Using modals for everything.**
+
+## Practice Time
+
+1. Open the **What Can Your Browser Do?** tab. How many features does your browser support? Which, if any, are missing?
+2. Open the same page in a second browser, and compare.
+3. Complete the **Old Way or New Way?** matcher.
+4. Choose one feature from the table, and look it up on MDN. What does its browser compatibility table say?
+5. Write the feature check you would use for `inert`.
+6. Pick a page of yours, and find one thing built by hand that a modern feature could replace.
+7. Write one sentence about a fallback for that feature.
+8. Bonus: find the Baseline label for `popover` on MDN.
+
+## Quick Recap
+
+Click a question to check your answer.
+
+
+1. What does "living standard" mean?
+
+HTML is no longer released in numbered versions. The specification is updated continuously, and browsers add features one by one.
+
+
+
+
+2. How do you know a feature is safe to use?
+
+Check browser support on MDN, Baseline, or Can I use, and think about which browsers your visitors really use.
+
+
+
+
+3. What is progressive enhancement?
+
+Building a page that works with plain, widely supported HTML, then adding newer features on top, so visitors without them still get a working page.
+
+
+
+
+4. Why detect a feature instead of a browser?
+
+Feature checks answer the question you care about, and they stay correct as browsers change. Browser names can be wrong or disguised.
+
+
+
+
+5. Do modern features remove the need for security habits?
+
+No. `template`, components, `dialog`, and `popover` still need escaping of visitor text, and none of them is a security boundary.
+
+
+
+
+6. Why prefer a built-in feature to hand-written code?
+
+It is usually shorter, faster, tested by browser makers, and brings keyboard and screen reader behaviour with it.
+
+
+
+## Key Takeaways
+
+- **HTML is a living standard.** Features arrive over time, and support varies by browser.
+- **Check support** on MDN, Baseline, or Can I use, and think about your visitors.
+- **Let HTML do what it can:** dialogs, disclosure, popovers, templates, slots, inert regions, lazy loading, and components.
+- **Build a working base first,** then enhance it.
+- **Detect features, not browsers.**
+- **Modern does not mean safe.** Keep escaping, and keep testing with the keyboard.
+
+Next up: [The HTML Living Standard](./modern-html/html-living-standard), where you will learn how HTML is specified, where to read it, and how a feature travels from an idea to your browser.
\ No newline at end of file
diff --git a/tutorials/html/17-modern-html/inert.mdx b/tutorials/html/17-modern-html/inert.mdx
new file mode 100644
index 000000000..e69de29bb
diff --git a/tutorials/html/17-modern-html/lazy-loading.mdx b/tutorials/html/17-modern-html/lazy-loading.mdx
new file mode 100644
index 000000000..e69de29bb
diff --git a/tutorials/html/17-modern-html/modern-html-features.mdx b/tutorials/html/17-modern-html/modern-html-features.mdx
new file mode 100644
index 000000000..b441ff3ff
--- /dev/null
+++ b/tutorials/html/17-modern-html/modern-html-features.mdx
@@ -0,0 +1,499 @@
+---
+id: html-modern-features
+title: "Modern HTML Features"
+sidebar_label: "Modern HTML Features"
+sidebar_position: 3
+slug: /html/modern-html/modern-html-features
+description: "A guided tour of newer HTML features that deserve a place in your toolbox: the search element, inputmode and enterkeyhint, fetchpriority and decoding, hidden until-found, translate and spellcheck, and module scripts with import maps. Plus a simple method for judging whether a feature is ready for your visitors. Includes a feature-matching quiz and a readiness judge."
+keywords:
+ - modern HTML features
+ - search element
+ - inputmode enterkeyhint
+ - fetchpriority
+ - hidden until-found
+ - translate no
+ - import maps
+ - script type module
+ - Baseline browser support
+ - learn HTML
+ - CodeHarborHub HTML
+tags: [html, web-development, beginner, modern-html, attributes, progressive-enhancement, baseline, frontend]
+---
+
+import {useState} from 'react';
+
+export const featureOptions = [
+ "translate=\"no\"",
+ "inputmode",
+ "enterkeyhint",
+ "hidden=\"until-found\"",
+ "fetchpriority=\"high\"",
+ "spellcheck=\"false\"",
+ "the search element",
+ "decoding=\"async\""
+];
+
+export const featureItems = [
+ {goal: "Stop a brand name or a snippet of code from being translated by a page translator", answer: "translate=\"no\""},
+ {goal: "Show a numeric keyboard on phones for a code field, without a number spinner", answer: "inputmode"},
+ {goal: "Change the label of the enter key on a phone keyboard to Search or Send", answer: "enterkeyhint"},
+ {goal: "Keep a section collapsed, but let find-in-page open it when the text matches", answer: "hidden=\"until-found\""},
+ {goal: "Tell the browser that the main hero image is more important than other images", answer: "fetchpriority=\"high\""},
+ {goal: "Stop the browser from underlining a username or a product code as a spelling mistake", answer: "spellcheck=\"false\""},
+ {goal: "Mark the part of the page that holds the site's search form as a landmark", answer: "the search element"},
+ {goal: "Let the browser decode an image away from the main flow of work so scrolling stays smooth", answer: "decoding=\"async\""}
+];
+
+export function FeatureMatcher() {
+ const [picked, setPicked] = useState({});
+ const [checked, setChecked] = useState(false);
+ const correct = featureItems.filter(function (it, i) { return picked[i] === it.answer; }).length;
+ return (
+
+ );
+}
+
+export const statusText = {
+ widely: "It works in all the major browsers, and has for a long time.",
+ newly: "It works in the latest versions of the major browsers, but older versions are still in use.",
+ limited: "Only some browsers support it."
+};
+
+export const audienceText = {
+ current: "Your visitors mostly use current phones and computers.",
+ mixed: "Your visitors include older or shared devices.",
+ old: "Some visitors must use very old browsers, such as a kiosk or an office computer that is not updated."
+};
+
+export function decideReadiness(status, degrades, audience) {
+ let verdict;
+ if (status === "widely") {
+ if (audience === "old") verdict = degrades ? "Use it as an enhancement" : "Use it only with a fallback";
+ else verdict = "Use it";
+ } else if (status === "newly") {
+ if (audience === "current") verdict = degrades ? "Use it as an enhancement" : "Use it only with a fallback";
+ else verdict = degrades ? "Use it as an enhancement" : "Wait";
+ } else {
+ if (degrades && audience !== "old") verdict = "Use it as an enhancement";
+ else verdict = "Wait";
+ }
+ const advice = {
+ "Use it": "Write it normally, and keep testing in more than one browser.",
+ "Use it as an enhancement": "Build a page that works without it, and let the feature improve things where it is available.",
+ "Use it only with a fallback": "The page needs the feature to work, so provide a fallback, such as a different element, a polyfill, or a simple alternative.",
+ "Wait": "The risk is higher than the benefit. Revisit it when support has spread, or choose a widely supported alternative."
+ };
+ return {verdict: verdict, advice: advice[verdict], reasons: [statusText[status], audienceText[audience], degrades ? "If the feature is missing, the page still works." : "If the feature is missing, part of the page stops working."]};
+}
+
+export function ReadinessJudge() {
+ const [status, setStatus] = useState("newly");
+ const [audience, setAudience] = useState("mixed");
+ const [degrades, setDegrades] = useState(true);
+ const r = decideReadiness(status, degrades, audience);
+ const colors = {"Use it": "#1e8449", "Use it as an enhancement": "#1e8449", "Use it only with a fallback": "#b9770e", "Wait": "#c0392b"};
+ return (
+
+
+
+
+
+
{r.verdict}
+
{r.advice}
+
+ {r.reasons.map(function (t) { return
{t}
; })}
+
+
+
+ A rule of thumb, not a law. Your own visitor numbers and the cost of a failure should decide the final choice.
+
+
+ );
+}
+
+HTML keeps growing. Alongside big features such as `dialog` and `popover`, which have lessons of their own, there is a set of **small, practical additions** that make forms friendlier, pages faster, and content easier to use for a global audience. This lesson is a guided tour of them, followed by a method for judging whether any new feature is ready for **your** site.
+
+## What You Will Learn
+
+- The `search` element, a landmark for search forms
+- `inputmode` and `enterkeyhint`, which shape the phone keyboard
+- `fetchpriority` and `decoding`, hints for images and resources
+- `hidden="until-found"`, `translate`, and `spellcheck`
+- Module scripts and import maps
+- A simple way to decide whether a feature is ready
+
+
+
+
+## The Big Idea
+
+Most modern features are **hints and improvements**, not new building blocks. If you add them to a solid page, browsers that understand them give visitors a better experience, and browsers that do not simply ignore them. That is the safest way to adopt new HTML.
+
+
+
+
+```html title="index.html"
+
+
+
+
+
+ Bakery
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Our shop is called DoughNation.
+
+
+
+
+
+
+```
+
+
+
+
+
+<>
+
+>
+
+
+
+
+
+
+<>
+
+>
+
+
+
+
+
+:::info
+Browser support changes over time. The notes in this lesson describe how each feature behaves, not a fixed support table. Before you rely on one, check its **Baseline** label and compatibility table on MDN, as explained in the [Modern HTML overview](/tutorials/html/modern-html).
+:::
+
+## The search Element
+
+The `search` element marks the part of a page that holds search or filtering controls. It gives assistive technology a **search landmark**, so screen reader users can jump straight to it.
+
+```html
+
+
+
+```
+
+Before it existed, you wrote `