Salesforce Certified JavaScript Developer Practice Questions

Salesforce Certified JavaScript Developer exam preparation

Salesforce Certified JavaScript Developer practice questions in English: 180 questions with explanations. The mock exam has 60 questions and 105 minutes.

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?

  1. div.innerHTML = comment.slice(0, 200);
  2. div.insertAdjacentHTML('beforeend', comment);
  3. div.innerHTML = comment;
  4. 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.

Go to the Salesforce Certified JavaScript Developer practice app (10 free questions; purchase unlocks all questions)

See the full practice set