CodePark/ questions / Frontend security
START PRACTICINGPRACTICE
Frontend question · Browser & web performance › Frontend security

name comes from a URL parameter. Which line is safe to use?

const name = new URLSearchParams(location.search).get("name");
// A: greeting.innerHTML = "Hello " + name;
// B: greeting.textContent = "Hello " + name;
// C: greeting.outerHTML = "<p>Hello " + name + "</p>";
// D: document.write("Hello " + name);
B

textContent inserts plain text, so any markup shows on screen as text. Nothing runs.

The other lines parse the value as HTML.
innerHTML is the tempting wrong answer, because innerHTML won't run a <script> tag. But a payload like <img src=x onerror=alert(1)> still runs. The broken image fires onerror, and the attacker's code executes.