learn.web Back to the curriculum ↗

HTML / CSS / JavaScript / 04

JavaScript as enhancement

Build with modules, events, workers, the Navigation API, Trusted Types, and capability detection.

Time
95 min
Mode
Learn → Make → Check
Path
Modern Web Platform

By the end, you can…

Enhancement must not erase the browser

JavaScript can make an interaction faster while accidentally breaking deep links, Back and Forward, refresh, focus, or open-in-new-tab. Start with real URLs and form submissions. Intercept only when the enhanced path is available, and update history in a way the browser can restore.

Capability detection asks whether the needed API exists. Browser sniffing guesses from a name and version, then becomes stale. A small feature test and a working fallback are easier to reason about.

Treat HTML injection as a security boundary

innerHTML and similar sinks interpret strings as markup. If an attacker can influence the string, they may create executable or misleading content. Prefer textContent and DOM construction. When an application genuinely needs HTML, sanitize it and consider enforcing Trusted Types.

Security is not a final audit. The safest interface makes the dangerous path difficult to call and the ordinary path safe by default.

Working example
const update = () => {
  document.querySelector("output").textContent = userValue;
};

if ("navigation" in window) {
  navigation.addEventListener("navigate", enhanceNavigation);
}

Your studio task

Make — Add client-side navigation or filtering without taking ownership away from links and history.

  1. Find one interaction that changes URL or page content.
  2. Confirm the unenhanced link or form works.
  3. Add the enhancement using capability detection.
  4. Test Back, Forward, refresh, focus restoration, and an untrusted string.
Definition of done

Back, forward, refresh, deep links, and keyboard activation remain reliable.

Open the interactive lesson with its workspace ↗

Knowledge check

Which assignment is safest for displaying untrusted plain text?
  1. element.innerHTML = value
  2. element.outerHTML = value
  3. element.textContent = value
Reveal answer (C)

textContent displays text without parsing it as markup.

What is the safest way to show untrusted plain text?
  1. element.textContent = value
  2. element.innerHTML = value
  3. document.write(value)
Reveal answer (A)

textContent renders the value as text; innerHTML and document.write parse it as markup.