2011-05-02 5 views
5

JavaScript를 통해 브라우저에 HTML을 전달하고 jQuery로 구문 분석 할 수는 있지만 외부 리소스를로드 할 수 있습니까? (스크립트, 이미지, 플래시, 기타)브라우저에서 리소스를로드하지 않고 jQuery의 구문을 분석하십시오.

가능하면 최선을 다해서 XML 파서를 사용 하겠지만 가능하면 느슨한 HTML을 허용하고 싶습니다.

Chrome, Firefox, 최신 IE와 호환되어야합니다.

+0

나는이 문제를 해결했다. 당신은 어떤 태그에 대해서도 src를 대체 할 수있다. http://stackoverflow.com/questions/6671461/replace-img-elements-src-attribute-in-regex – samccone

+0

나는 그렇지 않다. 소스 HTML을 제어하고, 까다로운 해킹이 너무 많습니다. 정규식 응답을 받아 들일 수 없습니다. 죄송합니다. 또한 외부 리소스를 자체적으로로드하기로 결정할 수 있으므로 스크립트를 실행하면 안됩니다. –

답변

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)); 

... 안돼 외부 연결하지 않으려면 어떤

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)); 

이 SRC, HREF 링크, 데이터 foo는 일치 작업 편집

테스트. http와 https가 일치합니다. 인라인 스크립트가 삭제됩니다. 여전히 보안 문제가 있다면 서버 측에서 수행하거나 JS를 난독 처리해야합니다.

+0

흥미로운 솔루션이지만 보안에 특히 좋지는 않습니다. 미안하지만 대답은 "블랙리스트 없이는 할 수 없다"는 것 같습니다. –

+0

외부에서는 항상 스크립트 도메인 이외의 도메인에서 호스팅되는 것을 의미합니까? 아니면 단일 HTML 파일에 표시 할 수없는 요소를 의미합니까? –

+0

구문 분석이 수행 될 때 어떤 네트워크 작업도 수행하지 않고 모든 스크립트를 실행하지 않으려합니다. –

관련 문제