美文网首页金鹏堡
DOMPurify 简单使用

DOMPurify 简单使用

作者: 沐青之枫 | 来源:发表于2018-01-30 15:47 被阅读34次

    DOMPurify – 针对 HTML、MathML 和 SVG 的仅支持DOM、快速、高容错的 XSS 过滤器

    实例:提交表单,设置XSS过滤

    原代码:

    <body>
        <div class="container">
            <form class="add-comment">
                <textarea class="comment-text"></textarea>
                <br>
                <button class="btn btn-primary" value="submit">Post Comment</button>
            </form>
            <div class="comment"></div>
        </div>
        <script>
            const addCommentForm = document.querySelector('.add-comment');
            const textarea = document.querySelector('.comment-text');
            const commentDiv = document.querySelector('.comment');
            const user = '';
            addCommentForm.addEventListener('submit', function (event) {
                event.preventDefault(); //取消事件的默认动作
                const newConmment = textarea.value.trim();
                if (newConmment) {
                    commentDiv.innerHTML =
                        `
                        <div class=" comment-header">${user}</div>
                        <div class="comment-body">${textarea.value}</div>
                        `
                    textarea.value = ``;
                }
            })
        </script>
    </body>
    

    引入purify.js后代码

    <body>
        <div class="container">
            <form class="add-comment">
                <textarea class="comment-text"></textarea>
                <br>
                <button class="btn btn-primary" value="submit">Post Comment</button>
            </form>
            <div class="comment"></div>
        </div>
        <script src="https://cdn.bootcss.com/dompurify/1.0.3/purify.js"></script>
        <script>
            function sanitize(strings, ...values) {
                const dirty = strings.reduce((prev, curr, i) => `${prev}${curr}${values[i] || ''}`, '');
                return DOMPurify.sanitize(dirty);
            }
            const addCommentForm = document.querySelector('.add-comment');
            const textarea = document.querySelector('.comment-text');
            const commentDiv = document.querySelector('.comment');
            const user = '';
    
            addCommentForm.addEventListener('submit', function (event) {
                event.preventDefault(); //取消事件的默认动作
                const newConmment = textarea.value.trim();
                if (newConmment) {
                    commentDiv.innerHTML = sanitize`
                        <div class=" comment-header">${user}</div>
                        <div class="comment-body">${textarea.value}</div>
                        `
                    textarea.value = ``;
                }
            })
        </script>
    </body>
    

    相关文章

      网友评论

        本文标题:DOMPurify 简单使用

        本文链接:https://www.haomeiwen.com/subject/zcjczxtx.html