4

所以我有这个功能可以从页面中删除脚本,但是一些多行的脚本仍然出现。有没有办法从加载的页面中删除所有脚本。

 function filterData(data){

// filter all the nasties out
// no body tags
data = data.replace(/<?\/body[^>]*>/g,'');
// no linebreaks
data = data.replace(/[\r|\n]+/g,'');
// no comments
data = data.replace(/<--[\S\s]*?-->/g,'');
// no noscript blocks
data = data.replace(/<noscript[^>]*>[\S\s]*?<\/noscript>/g,'');
// no script blocks
data = data.replace(/<script[^>]*>[\S\s]*?<\/script>/g,'');
// no self closing scripts
data = data.replace(/<script.*\/>/,'');

// [... add as needed ...]
return data;
  }

以下是 html 中的脚本示例

<script type="text/javascript">
var ccKeywords="keyword=";
if (typeof(ccauds) != 'undefined')
{
 for (var cci = 0; cci < ccauds.Profile.Audiences.Audience.length; cci++)
{
  if (cci > 0) ccKeywords += "&keyword="; ccKeywords +=     ccauds.Profile.Audiences.Audience[cci].abbr;
}
}
</script>
4

3 回答 3

2

如果我猜对了,您需要<script>从一段 HTML 字符串中删除所有带有内部代码的标签。在这种情况下,您可以尝试以下正则表达式:

data.replace(/<script.*?>[\s\S]*?<\/script>/ig, "");

它应该可以成功地与单行和多行一起使用,并且不会影响其他标签。

演示:http: //jsfiddle.net/9jBSD/

于 2012-06-12T16:15:57.203 回答
0
function filterData(data){
    var root = document.createElement("body");
    root.innerHTML = data;

    $(root).find("script,noscript").remove();

    function removeAttrs( node ) {
        $.each( node.attributes, function( index, attr ) {
            if( attr.name.toLowerCase().indexOf("on") === 0 ) {
                node.removeAttribute(attr.name);
            }
        });
    }

    function walk( root ) {
        removeAttrs(root);
        $( root.childNodes ).each( function() {
            if( this.nodeType === 3 ) {
                if( !$.trim( this.nodeValue ).length ) {
                    $(this).remove();
                }
            }
            else if( this.nodeType === 8 ) {
                $(this).remove();
            }
            else if( this.nodeType === 1 ) {
                walk(this);
            }
        });
    }

    walk(root);

    return root.innerHTML; 
}

filterData("<script>alert('hello');</script></noscript></script><div onclick='alert'>hello</div>\n\n<!-- comment -->");
//"<div>hello</div>"
于 2012-06-12T16:37:17.537 回答
0

结帐 Sugar.js - http://sugarjs.com/

它有一个 removeTags 方法,应该做你想做的事

http://sugarjs.com/api/String/removeTags

于 2012-06-12T15:57:36.570 回答