浏览器为jQuery解析HTML而不加载资源

Bry*_*eld 5 html xml browser jquery parsing

是否可以通过JavaScript将HTML传递给浏览器并使用jQuery解析它,但不能加载外部资源?(脚本,图像,flash,任何东西)

我将使用XML解析器,如果这是我能做的最好的,但我想尽可能允许松散的HTML.

它必须与Chrome,Firefox,最新的IE兼容.

Kyl*_*cey 1

var html = someHTML; //passed in html, maybe $('textarea#id').val();? I don't understand what you mean by 'passed in html'
var container = document.createElement('div');
container.innerHTML = html;
$(container).find('img,embed,head,script,style').remove();
//or
$(container).find('[src]').remove();

var target = someTarget; //place to put parsed html
$(container).appendTo($(target));
Run Code Online (Sandbox Code Playgroud)

编辑

经过测试工作

removeExt = function(cleanMe) {
    var toScrutinize = $(cleanMe).find('*'); //get ALL elements
    $.each(toScrutinize, function() {
      var attr = $(this)[0].attributes; //get all the attributes
      var that = $(this); 
      $.each(attr, function(){
          if ($(that).attr(this.nodeName).match(/^http/)) {//if the attribute value links externally
           $(that).remove(); //...take it out  
          } 
      })
    })
    $('script').remove(); //also take out any inline scripts
}

var html = someHTML;
var container = document.createElement('div');
container.innerHTML = html;
removeExt($(container));
var target = someTarget;
$(container).appendTo($(target));
Run Code Online (Sandbox Code Playgroud)

这将匹配 src、href、link、data-foo 等等...无法外部链接。http 和 https 都匹配。内联脚本被杀死。如果这仍然是一个安全问题,那么也许应该在服务器端完成,或者混淆你的 JS。