从HTML数据中删除脚本...使用JavaScript

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>

<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> - Blynn
Blynn,请将此内容放在您的原始问题中,而不是评论中。 - Blazemonger
我必须承认,我只在这种情况下使用jQuery... data = $("<div>" + data + "</div>").find('script').remove().end().html() - Angry Dan
3个回答

2

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

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

它应该能够成功地处理单行和多行,并且不会影响其他标签。

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


0

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>"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接