const untrustedStringFromUser = `<!doctype html><script src="http://evil.com/naughty.js"></script>`;
const iframe = document.createElement("iframe");
iframe.srcdoc = untrustedStringFromUser;
document.body.appendChild(iframe);HTMLIFrameElement: srcdoc property / notebook
HTMLIFrameElement: srcdoc property
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
<iframe
id="example"
srcdoc="<!doctype html><body><p>Hello World!</p></body>"></iframe>const frame = document.querySelector("#example");
const frameDoc = frame.srcdoc;
console.log(frameDoc); // "<!doctype html><body><p>Hello World!</p></body>"if (typeof trustedTypes === "undefined")
trustedTypes = { createPolicy: (n, rules) => rules };const policy = trustedTypes.createPolicy("my-policy", {
createHTML: (input) => DOMPurify.sanitize(input),
});// The potentially malicious string
const untrustedString =
"<!doctype html><body><p>I might be XSS</p><img src='x' onerror='alert(1)'></body>";
// Create a TrustedHTML instance using the policy
const trustedHTML = policy.createHTML(untrustedString);
// Inject the TrustedHTML (which contains a trusted string)
const frame = document.querySelector("#example");
const frameDoc = frame.srcdoc;