所以我有这个功能从页面中删除脚本,但是一些很多行的脚本仍然出现。有没有办法从加载的页面中删除所有脚本。
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>
答案 0 :(得分:2)
如果我说得对,你需要从HTML字符串中删除内部代码的所有<script>
标签。在这种情况下,您可以尝试以下正则表达式:
data.replace(/<script.*?>[\s\S]*?<\/script>/ig, "");
它应该成功地使用单行和多行,并且不会影响其他标记。
答案 1 :(得分:0)
checkout sugar.js - http://sugarjs.com/
它有一个removeTags方法,可以做你想做的事情
答案 2 :(得分: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>"