想要得到html檔案的原始碼,最直觀的做法就使用:
document.getElementsByTagName('html')[0].innerHTML
和
document.documentElement.innerHTML
或
document.documentElement.outerHTML
但是這樣無法得到第三方JavaScript所生成的html content
於是可以使用以下函式:
function DOMtoString(document_root) {
var html = '',
node = document_root.firstChild;
while (node) {
switch (node.nodeType) {
case Node.ELEMENT_NODE:
html += node.outerHTML;
break;
case Node.TEXT_NODE:
html += node.nodeValue;
break;
case Node.CDATA_SECTION_NODE:
html += '<![CDATA[' + node.nodeValue + ']]>';
break;
case Node.COMMENT_NODE:
html += '<!--' + node.nodeValue + '-->';
break;
case Node.DOCUMENT_TYPE_NODE:
// (X)HTML documents are identified by public identifiers
html += "<!DOCTYPE " + node.name
+ (node.publicId ? ' PUBLIC "' + node.publicId + '"' : '')
+ (!node.publicId && node.systemId ? ' SYSTEM' : '')
+ (node.systemId ? ' "' + node.systemId + '"' : '') + '>\n';
break;
}
node = node.nextSibling;
}
return html;
}
參數document_root,表示使用上述方法所獲取的html content。
顧名思義,此函式將會回傳包括JavaScript動態生成的html content。