Browser Security

Updated · 10 min read
mediumES2026javascriptsecurityxsscspinterview

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, createElement and setAttribute; if you must accept HTML, sanitize it with a tested library.
  • Never eval or new Function strings 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)

TypeHow the attacker's text arrives
Stored XSSSaved on the server (a student name, a comment) and shown to other users
Reflected XSSIn a link: the page copies part of the URL into its HTML
DOM-based XSSEntirely 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:

dom-xss.html
<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>
Output
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 dataSafe alternative
el.innerHTML = data, outerHTML, insertAdjacentHTMLel.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 inputSet 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:

safe-url.js▶ Try it
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));
}
Output
/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.com

Parsing 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:

sanitize.js
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:

eval.js▶ Try it
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");
Output
120
20

Use 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:

A strict CSP header
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'
DirectiveEffect
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-srcWhere 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:

trusted-types.js
const policy = trustedTypes.createPolicy("fee-tracker", {
  createHTML: (input) => DOMPurify.sanitize(input),
});
noteElement.innerHTML = policy.createHTML(userHtml);   // allowed
noteElement.innerHTML = userHtml;                       // TypeError under enforcement

This 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:

Headers
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.

DefenseHow
Load fewer third-party scriptsEach one is a full-trust dependency
Self-host librariesInstall 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 versionsNever load "latest"
Isolate widgetsPut them in sandboxed iframes on another origin
Restrict with CSPList exactly which origins may serve scripts
sri.html
<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 featureProtects against
Strict-Transport-SecurityDowngrading to unencrypted HTTP
X-Content-Type-Options: nosniffBrowsers treating a file as a different type (such as running an upload as a script)
Referrer-Policy: strict-origin-when-cross-originLeaking full URLs to other sites
Permissions-PolicyEmbedded content using camera, microphone or location
iframe sandboxEmbedded 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:

notes.html
<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>
Output
0 injected elements
1 safe link

Common 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
comment.html
<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>
Output
1 0 Srihitha: <script>steal()</script> Paid in full

Note 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.

Quick check: Browser security

3 questions
1Which is a dangerous sink for untrusted data?
2Why must user-supplied URLs be checked before use in a link?
3What does a strict Content Security Policy do?

Key Takeaways

ThreatMain defense
XSStextContent, sanitizer, no eval
Malicious linksProtocol allowlist with URL
Injected scriptsStrict CSP with nonces
Unsafe sink assignmentsTrusted Types
Clickjackingframe-ancestors
Compromised CDNSelf-hosting, Subresource Integrity

Was this tutorial helpful?

Lesson 124 of 139