Browser Security
Browser security is about stopping attackers from running their code in your users' browsers, or tricking those browsers into acting for them. The most important threat is cross-site scripting (XSS): if attacker-controlled text ever becomes code in your page, the attacker can read whatever the user sees, act as the user, and steal data. This lesson covers how XSS happens, the habits that prevent it, and the browser features that add layers of defense: Content Security Policy, Trusted Types, protections against clickjacking, and control of third-party scripts.
In One Minute
- XSS happens when untrusted data reaches an HTML or code sink:
innerHTML,outerHTML,insertAdjacentHTML,document.write,eval,javascript:URLs, event handler attributes. - Insert data with
textContent,createElementandsetAttribute; if you must accept HTML, sanitize it with a tested library. - Never
evalornew Functionstrings that contain outside data; avoid them entirely. - Content Security Policy (CSP) limits which scripts can run; Trusted Types make the browser reject unsafe sink assignments.
- Block clickjacking with
frame-ancestors, and load third-party scripts with pinned versions and integrity checks.
Cross-Site Scripting (XSS)
| Type | How the attacker's text arrives |
|---|---|
| Stored XSS | Saved on the server (a student name, a comment) and shown to other users |
| Reflected XSS | In a link: the page copies part of the URL into its HTML |
| DOM-based XSS | Entirely in the browser: JavaScript reads the URL, storage or a message and writes it into a sink |
All three end the same way: text the attacker controls is treated as markup or code. Here is DOM-based XSS from a URL parameter:
<p id="greeting"></p>
<p id="safe"></p>
<script>
const params = new URLSearchParams('?name=<img src=x onerror="console.log(`stole: ${document.title}`)">');
document.title = "Fee Tracker (logged in as Navika)";
document.querySelector("#greeting").innerHTML = `Hello, ${params.get("name")}`;
document.querySelector("#safe").textContent = `Hello, ${params.get("name")}`;
</script>stole: Fee Tracker (logged in as Navika)Explanation: the innerHTML line turned the parameter into a real <img> whose onerror ran attacker code with full access to the page (here it read the title; it could read anything). The textContent line displayed the same text harmlessly.
Safe Sinks and Dangerous Sinks
| Dangerous with untrusted data | Safe alternative |
|---|---|
el.innerHTML = data, outerHTML, insertAdjacentHTML | el.textContent = data; createElement + textContent |
document.write(data) | DOM methods |
eval(data), new Function(data), setTimeout("code") | Real functions; JSON.parse for data |
el.setAttribute("onclick", data) | addEventListener with a function |
a.href = data, iframe.src = data (a javascript: URL runs code) | Validate the URL's protocol first |
el.style.cssText = data with user input | Set individual properties with validated values |
jQuery $(data), .html(data) | .text(data) |
URLs Need Checking Too
textContent doesn't help for attributes that load or run things. A link to javascript:alert(1) runs code when clicked. Allow only safe protocols:
function safeUrl(input, base = "https://www.example.com") {
try {
const url = new URL(input, base);
return ["https:", "http:", "mailto:"].includes(url.protocol) ? url.href : null;
} catch {
return null;
}
}
for (const input of ["/fees/report", "https://example.org/help", "javascript:alert(1)", "JaVaScRiPt:alert(1)", "data:text/html,<script>", "mailto:navika@example.com"]) {
console.log(input.padEnd(28), safeUrl(input));
}/fees/report https://www.example.com/fees/report
https://example.org/help https://example.org/help
javascript:alert(1) null
JaVaScRiPt:alert(1) null
data:text/html,<script> null
mailto:navika@example.com mailto:navika@example.comParsing with URL normalizes tricks like mixed case, which simple string checks miss.
When You Must Allow HTML: Sanitize
Some features legitimately accept rich text (a formatted note, a description). Never write your own HTML filter with regular expressions: attackers know dozens of ways around them. Use a maintained sanitizer such as DOMPurify, which parses the HTML and keeps only allowed elements and attributes:
import DOMPurify from "dompurify";
const clean = DOMPurify.sanitize(userHtml, { ALLOWED_TAGS: ["b", "i", "em", "strong", "p", "ul", "li", "a"] });
noteElement.innerHTML = clean;Browsers are adding a built-in sanitizer: the HTML Sanitizer API (element.setHTML(html), which removes script-capable content), which runs in Chromium 158 (checked November 2026) but not in Playwright's WebKit build. Check support and keep a library fallback.
eval and Friends
eval(string) runs a string as code with access to the surrounding scope. new Function(string), setTimeout(string) and setInterval(string) do similar things. With any outside data in the string, they're code injection; even without it, they're slow and blocked by a strict CSP:
const fromApi = '{"total": 120}';
console.log(JSON.parse(fromApi).total);
const operations = { add: (a, b) => a + b, multiply: (a, b) => a * b };
const op = "multiply";
console.log(operations[op]?.(4, 5) ?? "unknown operation");120
20Use JSON.parse for data, and a lookup table of real functions instead of building code from strings.
Content Security Policy
A Content Security Policy (CSP) is an HTTP response header that tells the browser which sources of scripts, styles, images and connections are allowed. Even if an attacker injects markup, a strict CSP stops their script from running:
Content-Security-Policy:
default-src 'self';
script-src 'self' 'nonce-r4nd0m';
object-src 'none';
base-uri 'none';
frame-ancestors 'none';
connect-src 'self' https://api.example.com;
require-trusted-types-for 'script'| Directive | Effect |
|---|---|
script-src 'self' 'nonce-...' | Only your own scripts, and inline scripts carrying this page load's random nonce, may run; inline event handlers and eval are blocked |
object-src 'none' | No plugins |
base-uri 'none' | Prevents changing the page's base URL |
frame-ancestors 'none' | No other site may embed the page (anti-clickjacking) |
connect-src | Where fetch and WebSockets may connect, limiting data exfiltration |
require-trusted-types-for 'script' | Enforces Trusted Types (below) |
A policy can first be deployed as Content-Security-Policy-Report-Only to collect violation reports without blocking anything, then switched on. CSP is a second layer: it reduces the damage of a bug, but the first layer is still not writing user data into HTML.
Trusted Types
Trusted Types turn dangerous sinks into errors unless the value went through a policy you defined. With require-trusted-types-for 'script' in the CSP, el.innerHTML = someString throws; only objects created by your sanitizing policy are accepted:
const policy = trustedTypes.createPolicy("fee-tracker", {
createHTML: (input) => DOMPurify.sanitize(input),
});
noteElement.innerHTML = policy.createHTML(userHtml); // allowed
noteElement.innerHTML = userHtml; // TypeError under enforcementThis makes every HTML-writing location in a codebase visible and reviewable. As of November 2026, window.trustedTypes exists in Chromium 158 and in Playwright's WebKit build (checked by running them); check MDN's compatibility table for the exact browser versions you support. Where unsupported, the CSP directive is ignored, so keep the safe coding habits regardless.
Clickjacking
Clickjacking hides your page in an invisible frame on an attacker's site and tricks users into clicking your buttons ("Confirm payment") while they think they're clicking something else. Defend with a response header:
Content-Security-Policy: frame-ancestors 'self'
X-Frame-Options: DENY (older header, for older browsers)Third-Party Scripts
Every <script src> from another site runs with full access to your page: analytics, chat widgets, ad tags and CDN libraries can read forms and act as the user. If that provider is compromised, so are you.
| Defense | How |
|---|---|
| Load fewer third-party scripts | Each one is a full-trust dependency |
| Self-host libraries | Install from npm and serve them yourself |
| Subresource Integrity for CDN files | <script src="..." integrity="sha384-..." crossorigin="anonymous">: the browser refuses a changed file |
| Pin exact versions | Never load "latest" |
| Isolate widgets | Put them in sandboxed iframes on another origin |
| Restrict with CSP | List exactly which origins may serve scripts |
<script
src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"
integrity="sha384-(the published hash for this exact file)"
crossorigin="anonymous"></script>Other Browser Protections
| Header or feature | Protects against |
|---|---|
Strict-Transport-Security | Downgrading to unencrypted HTTP |
X-Content-Type-Options: nosniff | Browsers treating a file as a different type (such as running an upload as a script) |
Referrer-Policy: strict-origin-when-cross-origin | Leaking full URLs to other sites |
Permissions-Policy | Embedded content using camera, microphone or location |
iframe sandbox | Embedded pages running scripts or navigating your page |
rel="noopener" (default for target="_blank" in modern browsers) | Opened pages controlling yours through window.opener |
In Practice
The Fee Tracker's comment feature lets staff leave notes on a student. It renders notes as plain text, links only safe URLs, and builds every element with DOM methods, so no note can inject code:
<ul id="notes"></ul>
<script>
const notes = [
{ author: "Navika", text: "Paid by check <b>today</b>", link: "https://www.example.com/receipts/42" },
{ author: "Mallory", text: '<img src=x onerror="console.log(`hacked`)">', link: "javascript:console.log('hacked')" },
];
const safeUrl = (u) => { try { const x = new URL(u); return x.protocol === "https:" ? x.href : null; } catch { return null; } };
const list = document.querySelector("#notes");
for (const note of notes) {
const li = document.createElement("li");
li.append(`${note.author}: ${note.text} `);
const href = safeUrl(note.link);
if (href) {
const a = document.createElement("a");
a.href = href;
a.textContent = "receipt";
li.append(a);
}
list.append(li);
}
console.log(list.querySelectorAll("img, b").length, "injected elements");
console.log(list.querySelectorAll("a").length, "safe link");
</script>0 injected elements
1 safe linkCommon Mistakes
Escaping or filtering HTML by hand. Regular-expression filters are easy to bypass. Use textContent or a sanitizer.
Trusting data from your own server or database. It may contain what users typed. Encode at output.
Allowing user-supplied URLs unchecked. javascript: and data: URLs run code. Check the protocol.
Relying on CSP alone. It's a safety net, not a fix for unsafe code.
Interview Corner
What is XSS and how do you prevent it?
Cross-site scripting is injecting attacker-controlled script into a page viewed by other users, via stored data, reflected URL parameters or client-side DOM sinks. Prevent it by treating all external data as untrusted, writing it only through safe APIs (textContent, attribute setters, framework templating that escapes by default), validating URLs, sanitizing any allowed HTML with a vetted library, avoiding eval, and adding defense in depth with a strict CSP and Trusted Types.
What does Content Security Policy do?
CSP is a response header listing allowed sources for scripts, styles, connections, frames and more. A strict policy (nonces or hashes for scripts, no inline handlers, no eval) prevents injected scripts from executing, limits exfiltration through connect-src, and with frame-ancestors prevents clickjacking. It reduces the impact of XSS bugs but doesn't replace output encoding.
Practice
Challenge: Write renderComment(container, comment) that shows the author in bold (using a <strong> you create) and the text as plain text, so a comment containing HTML can't inject elements.
Show solution
<div id="c"></div>
<script>
function renderComment(container, { author, text }) {
const p = document.createElement("p");
const strong = document.createElement("strong");
strong.textContent = author;
p.append(strong, `: ${text}`);
container.append(p);
}
const box = document.querySelector("#c");
renderComment(box, { author: "Srihitha", text: "<script>steal()<\/script> Paid in full" });
console.log(box.querySelectorAll("strong").length, box.querySelectorAll("script").length, box.textContent);
</script>1 0 Srihitha: <script>steal()</script> Paid in fullNote the <\/script> in the source: inside an inline <script> element, the characters </script> end the element immediately, even inside a string, so they must be written with an escaped slash. That's one more reason to keep JavaScript in separate .js files.
Key Takeaways
| Threat | Main defense |
|---|---|
| XSS | textContent, sanitizer, no eval |
| Malicious links | Protocol allowlist with URL |
| Injected scripts | Strict CSP with nonces |
| Unsafe sink assignments | Trusted Types |
| Clickjacking | frame-ancestors |
| Compromised CDN | Self-hosting, Subresource Integrity |
Was this tutorial helpful?