2011-10-12 22 views
14

什麼是某些用例以及是否已棄用?當我發現在http://groups.google.com/group/envjs/browse_thread/thread/6c22d0f959666009/c389fc11537f2a97它的「非標,而不是由任何現代瀏覽器都支持」 ...什麼是使用document.implementation.createHTMLDocument?

編輯:

關於document.implementationhttp://javascript.gakaa.com/document-implementation.aspx

返回到基準W3C DOMImplementation對象,其中 在很大程度上代表構成文檔包含瀏覽器的環境,用於我們的目的。對象 的方法可讓您查看瀏覽器報告支持哪些DOM模塊。這個 對象也是在當前文檔樹之外創建虛擬W3C文檔和DocumentType對象的網關。因此,在 Netscape 6中,您可以使用document.implementation屬性作爲開始 爲外部XML文檔生成非呈文檔。請參閱 DOMImplementation對象,瞭解有關這些方法及其瀏覽器支持的詳細信息。

由於它提供的方法(如createHTMLDocument)當前文檔樹以外建立一個nonrendered文件,這將是安全的,給它不受信任的第三方HTML的輸入可能包含一些XSS?我問,因爲我想使用createHTMLDocument作爲第三方HTML輸入的遍歷目的。可能會成爲用例之一?

+1

根據[QuirksMode](http://www.quirksmode.org/dom/w3c_html.html),'createHTMLDocument'在舊版本的IE或Firefox。 IE9顯然支持它,而我自己的測試表明FF7支持它。 – lonesomeday

+1

['createHTMLDocument'在DOM2規範中](http://www.w3.org/TR/2000/CR-DOM-Level-2-20000510/html.html#ID-1019015399) – lonesomeday

回答

12

我一直用這個,因爲它沒有任何要求的圖像,執行腳本或影響造型:

function cleanHTML(html) { 
    var root = document.implementation.createHTMLDocument().body; 

    root.innerHTML = html; 

    //Manipulate the DOM here 
    $(root).find("script, style, img").remove(); //jQuery is not relevant, I just didn't want to write exhausting boilerplate code just to make a point 

    return root.innerHTML; 
} 


cleanHTML('<div>hello</div><img src="google"><script>alert("hello");</script><style type="text/css">body {display: none !important;}</style>'); 
//returns "<div>hello</div>" with the page unaffected 
+5

Exhause樣板代碼= '[] .forEach.call(document.querySelectorAll(「script,style,img」),function(el){el.remove();});' – Greg

9

是。您可以使用它加載不受信任的第三方內容,並在將其包含到自己的文檔中之前將其除去危險的標籤和屬性。有一些很好的研究結合了這個技巧,描述在http://blog.kotowicz.net/2011/10/sad-state-of-dom-security-or-how-we-all.html

然而,上面的Esailija記錄的技術不足。您還需要刪除大多數屬性。攻擊者可以將一個onerror或onmouseover元素設置爲惡意JS。 style屬性可以用來包含運行惡意JS的CSS。 Iframe和其他嵌入標籤也可能被濫用。查看https://html5sec.org/xssme/xssme2來源查看該技術的一個版本。

+0

[Second link](http://xssme.html5sec。 org/xssme2)已損壞。看到 – jscripter

+0

會很有趣,我認爲這是相同代碼的副本:https://html5sec.org/xssme/xssme2。更新答案以指向那裏。原始網址是http://xssme.html5sec.org/xssme2 – jsha

1

只是除了@Esailija和@格雷格答案更清潔的答案:

function insertDocument (myHTML) { 
    var newHTMLDocument = document.implementation.createHTMLDocument().body; 
    newHTMLDocument.innerHTML = myHTML; 
    [].forEach.call(newHTMLDocument.querySelectorAll("script, style, img"), function(el) {el.remove(); }); 
    documentsList.push(newHTMLDocument); 
    return $(newHTMLDocument.innerHTML); 
} 

: 此功能將創建當前文檔的樹之外的另一個文件,並從新建文檔清理所有的腳本,風格和圖片這對於製作Ajax請求來說太棒了,而且抓取內容的速度會更快:)