6

I want dompurify to allow iframe tags, and I add iframe as an exception(ADD_TAGS). But that removes some attributes of it. I want all attributes to be there.

<!doctype html>
<html>
    <head>
          <script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/1.0.3/purify.min.js"></script>    </head>
    <body>
        <!-- Our DIV to receive content -->
        <div id="sanitized"></div>

        <!-- Now let's sanitize that content -->
        <script>
            /* jshint globalstrict:true, multistr:true */
            /* global DOMPurify */
            'use strict';

            // Specify dirty HTML
            var dirty = '<iframe allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" height="315" scrolling="no" src="https://www.youtube.com/embed/vJG698U2Mvo" width="560"></iframe>';

            var config = { ADD_TAGS: ['iframe'], KEEP_CONTENT: false }

            // Clean HTML string and write into our DIV
            var clean = DOMPurify.sanitize(dirty, config);
            console.log('clean: ', clean)
            document.getElementById('sanitized').innerHTML = clean;
        </script>
    </body>
</html>

Here is the sanitized output

"clean: <iframe width='560' src='https://www.youtube.com/embed/vJG698U2Mvo' height='315'></iframe>"

2 Answers 2

10

If you want to only allow the iframe tags use ALLOWED_TAGS not ADD_TAGS which allows the default allowed tags and the iframe tag that is not allowed by default.

To allow all default tags and the iframe tag :

DOMPurify.sanitize(dirty, { ADD_TAGS: ["iframe"], ADD_ATTR: ['allow', 'allowfullscreen', 'frameborder', 'scrolling'] });

To allow only the iframe tag :

DOMPurify.sanitize(dirty, { ALLOWED_TAGS: ["iframe"], ADD_ATTR: ['allow', 'allowfullscreen', 'frameborder', 'scrolling'] });
1
  • it is still stripping away the various 'src', 'href', 'target' attributes for me.
    – S. W. G.
    Apr 16, 2022 at 8:47
0

If I understand the documentation correctly, you also need to register the necessary non-standard attributes that you want to keep using:

DOMPurify.sanitize(dirty, { ADD_ATTR: ['allow', 'allowfullscreen', 'frameborder', 'scrolling'] });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.