如何允许“dompurify”中的 iframe 标记包括其所有属性

Hen*_*aye 6 javascript dompurify

我想dompurify允许 iframe 标签,并添加iframe为例外 ( ADD_TAGS)。但这消除了它的一些属性。我希望所有属性都在那里。

<!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>
Run Code Online (Sandbox Code Playgroud)

这是经过净化的输出

"clean: <iframe width='560' src='https://www.youtube.com/embed/vJG698U2Mvo' height='315'></iframe>"
Run Code Online (Sandbox Code Playgroud)

小智 11

如果您只想允许 iframe 标记,请使用 ALLOWED_TAGS 而不是 ADD_TAGS,它允许默认允许的标记和默认情况下不允许的 iframe 标记。

允许所有默认标签和 iframe 标签:

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

仅允许 iframe 标记:

DOMPurify.sanitize(dirty, { ALLOWED_TAGS: ["iframe"], ADD_ATTR: ['allow', 'allowfullscreen', 'frameborder', 'scrolling'] });
Run Code Online (Sandbox Code Playgroud)


bho*_*eam 0

如果我正确理解文档,您还需要注册您想要继续使用的必要的非标准属性:

DOMPurify.sanitize(dirty, { ADD_ATTR: ['allow', 'allowfullscreen', 'frameborder', 'scrolling'] });
Run Code Online (Sandbox Code Playgroud)