Salesforce Certified JavaScript Developer free question 6 / 10 · Domain 3: Browser and Events
A page shows comments that visitors type into a form. A developer must display each comment inside a div without letting a comment run scripts or add markup. Which line is the safest way to write the comment?
- div.innerHTML = comment.slice(0, 200);
- div.insertAdjacentHTML('beforeend', comment);
- div.innerHTML = comment;
- div.textContent = comment;
Show the answer and explanation
Answer: D
Why this is correct
Setting innerHTML or calling insertAdjacentHTML parses a string as HTML and writes it into the DOM, so attacker-supplied input can become executable markup. textContent inserts the string as text and never parses it.
Why the other options are wrong
"div.innerHTML = comment;" … innerHTML parses its input as HTML, which makes it an injection sink and a possible vector for cross-site scripting if the text came from an attacker.
"div.insertAdjacentHTML('beforeend', comment);" … This method also parses its input as HTML, and the page lists it among the injection sinks with the same security warning.
"div.innerHTML = comment.slice(0, 200);" … Cutting the string to a maximum length does not stop markup from being parsed. A short script tag is still injected.
Key points
Treat HTML-parsing APIs as injection sinks. For user-supplied text use textContent.