Search code examples
javascriptxssdomparser

Is parsing HTML with DOMParser safe from XSS?


I am using the DOMParser in my code as such:

 html`${this.domParser.parseFromString(this.richText, 'text/html').body.children}`

After reading the documentation i became a bit worried that Cross site Scripting attacks were still possible because as the documentation states:

You can perform the opposite operation—converting a DOM tree into XML or HTML source—using the XMLSerializer interface.

However it also states that it returns

Either Document or XMLDocument depending on the mimeType argument.

So is using this method going good for securing your site against XSS?


Solution

  • In this introductory article on we can see that DOMParser#parseFromString is a known XSS sink.

    The <script> blocks won't execute but the parser is unable to tell what constitutes an XSS threat.

    You cannot use it to safely inject html into a page:

    const parser = new DOMParser();
    const html = '<img onerror="alert(`gotcha`)" src="">';
    const new_node = parser.parseFromString(html, 'text/html').body.firstChild;
    document.querySelector('div').appendChild(new_node);
    <div></div>


    How to sanitize HTML?

    You can use a purpose-built library such as :

    const dirty = '<img onerror="alert(`gotcha`)" src="">';
    const clean = DOMPurify.sanitize(dirty);
    
    console.log(clean);
    <script src="https://unpkg.com/dompurify@2.2.2/dist/purify.min.js"></script>