Skip to content Skip to sidebar Skip to footer

Can A "new Domparser.parsefromstring" Be Safer Than "createelement"?

I create a script for try remove insecure content (I'm using it for browser extensions): I'm using this script in an addon I created for opera and Google Chorme, however the site

Solution 1:

Effectively, your current code is not safe. innerHTML doesn't run scripts in created <script> elements, but it does run event handler content attributes.

functioncreateDOM(str) {
  document.createElement("div").innerHTML = str;
}
createDOM('<img src="//" onerror="console.log(\'You are pwned!\')" />');

functioncreateDOM(str) {
  newDOMParser().parseFromString(str, "text/html");
}
createDOM('<img src="//" onerror="console.log(\'You are safe\')" />');

However, note that DOMParser provides safety if you only want to manipulate the DOM elements from an untrusted HTML string. It's like a sandbox. But if then you get these elements and append it in the current document, they will still be able to run JS.

functioncreateDOM(str) {
  document.body.appendChild(newDOMParser().parseFromString(str, "text/html").body);
}
createDOM('<img src="//" onerror="console.log(\'You are pwned!\')" />');

If you really need something like this, I would use a small whitelist of allowed elements and attributes, and get rid of everything else.

Post a Comment for "Can A "new Domparser.parsefromstring" Be Safer Than "createelement"?"