Why document.write is flagged
document.write() writes text into the document stream while HTML is being parsed. Its behavior depends on timing and browser parsing state. It can block rendering, produce unpredictable results in deferred or asynchronous scripts, and overwrite the current page when called after loading.
MDN marks the method as deprecated and warns that it is an injection sink when untrusted input reaches it. New code should not use it.
Find the source
- Search first-party source, templates, tag-manager snippets, and generated HTML for document.write.
- Use browser developer tools to identify the script and call stack responsible for the call.
- Check advertising, analytics, consent, and legacy widget providers.
- Confirm whether the call runs during initial parsing or after the document has loaded.
Replace markup insertion
Create elements explicitly and add text through textContent when the value should not be interpreted as HTML.
const message = document.createElement('p');
message.textContent = statusText;
document.querySelector('[data-status]')?.append(message);
When trusted application markup must be rendered, use the framework or templating system already responsible for that part of the page. Avoid moving untrusted strings into innerHTML as a one-line replacement because that preserves the injection risk.
Replace script injection
const script = document.createElement('script');
script.src = 'https://example.com/widget.js';
script.async = true;
document.head.append(script);
Prefer the official modern integration offered by the provider. Preserve consent, integrity, nonce, and Content Security Policy requirements used by the site.
Third-party code you cannot edit
Ask the provider for an asynchronous or module-based snippet. Load the integration only on pages that need it. If the vendor offers no safe replacement, evaluate removal or an isolated implementation rather than suppressing the audit.
Security considerations
Never pass user-controlled input to document.write, innerHTML, insertAdjacentHTML, or a similar HTML parser without an appropriate sanitization and Trusted Types strategy. Use textContent for plain text and project-approved rendering utilities for markup.
Verify the replacement
Test with JavaScript enabled under slow-network conditions. Confirm that the same content appears, scripts execute once, analytics and consent still work, and no console or Content Security Policy errors are introduced. Compare rendering and performance before and after.
See the MDN Document.write reference for current browser and security guidance.