The below are my use case scenario.
- Collect the user input.(the input must be HTML sting element)
- Form the HTML element with some style.
- After creating the HTML element, need to sanitize it and append it into the target DOM element.
- The DOM element rendered the sanitized element. but the error alert stil displayed.
The user input is
<img src="http://url.to.file.which/not.exist" onerror="alert(document.cookie);">
This always shows the alert.
Can someone help me to resolve this?
function createEle() {
const wrapElement = document.createElement('div');
wrapElement.innerHTML = document.getElementById("html-input").value;
const html = showSanitizedHTML(wrapElement);
console.log(html.outerHTML)
document.getElementById("sanitized-html").innerHTML = html.innerHTML;
}
function showSanitizedHTML(value) {
const sanitizedHTML = DOMPurify.sanitize(value.outerHTML);
const tempWrapElement = document.createElement('div');
tempWrapElement.innerHTML = sanitizedHTML;
return tempWrapElement.firstElementChild;
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/purify.min.js"></script>
<textarea id="html-input"></textarea>
<button onclick="createEle()">Show Sanitized HTML</button>
<div id="sanitized-html"></div>
This is the sequence of events:
wrapElement.innerHTML =)The alert fires due to step 2.