如何在使用所见即所得编辑器之前删除不安全的内容

How to remove unsafe contents of WYSIWYG editors before use it?

本文关键字:删除 不安全 编辑器 所见即所得      更新时间:2023-09-26

如何在使用前删除所见即所得编辑器的不安全内容,如script标签或iframe标记和其他标签的事件

<script>
// Dangerous contents
</script>
<iframe>
// bad web pages
</iframe>
<span onclick="javascript://do bad work here !!!">click me</span>

您不应该试图自己编写这样的保护。

特别是,您不应该将保护放在客户端(javascript),而是使用服务器端过滤,如http://htmlpurifier.org/

我们可以使用像这样的javascript函数来中和

function neutralizeText(text) {
    var i,mtch=text.match(/(<[a-z]+'s+[^>]*'s+|<[a-z]+'s+)on[a-z]+('s)*=('b|'s|[^>])*>/gi);
    if(mtch!=null) {
        for(i=0;i<mtch.length;i++) {
            text=text.replace(mtch[i],mtch[i].replace(/'s+on[a-z]+('s)*=/gi,' data-neutralized='));
        }
    }
    text=text.replace(/<script('b|'s)[^>]*>(([ 't'r'n]|.)*?)<'/script>/ig,'');
    text=text.replace(/<iframe('b|'s)[^>]*>(([ 't'r'n]|.)*?)<'/iframe>/ig,'');
    text=text.replace(/<object('b|'s)[^>]*>(([ 't'r'n]|.)*?)<'/object>/ig,'');
    text=text.replace(/<'!'-'-(.*?)'-'->/g,'');
    text=text.replace(/<'!'-'-/g,'');
    return text;
}

但这还不够,您必须在服务器端进行检查。因为javascript可以在浏览器中禁用。