Use of document.write¶
Scope and impact¶
document.write parses strings as HTML and interacts with the document's parsing stream. Untrusted input can become markup or script. Calls after loading may also replace the document, and browser behavior depends on timing and context. It is a deprecated API to remove during maintenance; a fixed trusted string alone does not establish an injection vulnerability. See MDN's document.write reference.
Matched text-output example¶
Assume message is an untrusted string and container is an existing application-owned element. The intended feature displays a plain paragraph.
Unsafe: interpolate the message into HTML.
document.write('<p>' + message + '</p>');
Safer: keep the message in a text node.
const paragraph = document.createElement('p');
paragraph.textContent = message;
container.append(paragraph);
The second version creates a fixed element and assigns text without interpreting the message as HTML. textContent is appropriate for this plain-text context. The same construction pattern is not sufficient if subsequent code assigns untrusted HTML, event handlers or unsafe URL attributes.
When formatting is required¶
Keep presentation in application templates or explicitly created elements. If rich user-authored HTML is an actual requirement, use a maintained HTML sanitizer with an appropriate policy and review the final insertion context. Do not substitute character stripping, innerHTML or a trust-bypass call and call the migration complete.
Regression check¶
In a browser fixture, display a harmless string such as <em>sample</em> and confirm the literal characters appear, no em element is created, and existing page content remains. Check the normal loading flow as well as delayed updates. See HTML injection and autoescaping.