JS是否有办法将 html 标记内的整个HTML作为字符串获取?

document.documentElement.??
有帮助吗?

解决方案

MS不久前添加了outerHTMLinnerHTML属性。

根据 MDN ,<=>受支持Firefox 11,Chrome 0.2,Internet Explorer 4.0,Opera 7,Safari 1.3,Android,Firefox Mobile 11,IE Mobile,Opera Mobile和Safari Mobile。 <=>位于 DOM解析和序列化规范中。

有关适合您的浏览器兼容性,请参阅 quirksmode 。所有支持<=>。

var markup = document.documentElement.innerHTML;
alert(markup);

其他提示

你可以做到

new XMLSerializer().serializeToString(document)
在比IE 9更新的浏览器中

请参阅 https://caniuse.com/#feat=xml-serializer

我相信document.documentElement.outerHTML应该为你返回。

根据 MDN outerHTML受支持Firefox 11,Chrome 0.2,Internet Explorer 4.0,Opera 7,Safari 1.3,Android,Firefox Mobile 11,IE Mobile,Opera Mobile和Safari Mobile。 <=>位于 DOM解析和序列化规范中。

<=> property <<上的MSDN页面a>注意IE 5+支持它。 Colin的答案链接到W3C quirksmode页面,该页面提供了跨浏览器兼容性的良好比较(对于其他DOM功能)。

你也可以这样做:

document.getElementsByTagName('html')[0].innerHTML

你不会得到Doctype或html标签,但其他一切......

document.documentElement.outerHTML

可能只有IE:

>     webBrowser1.DocumentText

表示FF从1.0开始:

//serialize current DOM-Tree incl. changes/edits to ss-variable
var ns = new XMLSerializer();
var ss= ns.serializeToString(document);
alert(ss.substr(0,300));

可能在FF中有效。 (从源文本的非常开始,显示非常第一个300个字符,主要是doctype-defs。)

但要注意,正常的<!>“另存为<!>” - 对话的FF可能不会保存页面的当前状态,而是保存原始加载的X / h / tml-source-text! ! (将ss张贴到某个临时文件并重定向到该文件可能会提供一个可保存的源文本,其中包含之前所做的更改/编辑。)

虽然FF在<!>的回复中出现了惊人的回复<!>和<!>上的状态/值的NICE包含“保存(as)...... <!>”; 用于类似输入的FIELDS,textarea 等,而不是在contenteditable / designMode中的元素...

如果不是xhtml- resp。 xml-file(mime-type,而不仅仅是filename-extension!),可以使用document.open/write/close来设置appr。内容到源层,将从FF的文件/保存菜单保存在用户的保存对话框中。 看到: http://www.w3.org/MarkUp/2004/xhtml-faq#docwrite resp。

https://developer.mozilla.org/en-美国/文档/网络/ API /文件撰写

对X(ht)ML问题的中立,尝试<!>“view-source:http:// ... <!>”;作为(脚本制作的!?)iframe的src-attrib的值, - 访问FF中的iframes文档:

<iframe-elementnode>.contentDocument,请参阅google <!>; mdn contentDocument <!> quot;对于appr。成员,比如'textContent'。 “多年前就这样了,不喜欢爬行。如果仍然迫切需要,请提一下,我要潜入......

document.documentElement.innerHTML

我总是使用

document.getElementsByTagName('html')[0].innerHTML

可能不是正确的方式,但是当我看到它时我能理解它。

使用document.documentElement

同样的问题在这里回答: https://stackoverflow.com/a/7289396/2164160

除了<html>...</html>,最重要的是<!DOCTYPE ...>声明之外,您可以浏览document.childNodes,将每个变成一个字符串:

const html = [...document.childNodes]
    .map(node => nodeToString(node))
    .join('\n') // could use '' instead, but whitespace should not matter.

function nodeToString(node) {
    switch (node.nodeType) {
        case node.ELEMENT_NODE:
            return node.outerHTML
        case node.TEXT_NODE:
            // Text nodes should probably never be encountered, but handling them anyway.
            return node.textContent
        case node.COMMENT_NODE:
            return `<!--${node.textContent}-->`
        case node.DOCUMENT_TYPE_NODE:
            return doctypeToString(node)
        default:
            throw new TypeError(`Unexpected node type: ${node.nodeType}`)
    }
}

我在npm上将此代码发布为 document-outerhtml


编辑注意上面的代码取决于函数doctypeToString;它的实现如下(下面的代码在npm上发布为 doctype-to-string ):

function doctypeToString(doctype) {
    if (doctype === null) {
        return ''
    }
    // Checking with instanceof DocumentType might be neater, but how to get a
    // reference to DocumentType without assuming it to be available globally?
    // To play nice with custom DOM implementations, we resort to duck-typing.
    if (!doctype
        || doctype.nodeType !== doctype.DOCUMENT_TYPE_NODE
        || typeof doctype.name !== 'string'
        || typeof doctype.publicId !== 'string'
        || typeof doctype.systemId !== 'string'
    ) {
        throw new TypeError('Expected a DocumentType')
    }
    const doctypeString = `<!DOCTYPE ${doctype.name}`
        + (doctype.publicId ? ` PUBLIC "${doctype.publicId}"` : '')
        + (doctype.systemId
            ? (doctype.publicId ? `` : ` SYSTEM`) + ` "${doctype.systemId}"`
            : ``)
        + `>`
    return doctypeString
}

我只需要doctype html,并且应该可以在IE11,Edge和Chrome中正常使用。我使用下面的代码它工作正常。

function downloadPage(element, event) {
    var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);

    if ((navigator.userAgent.indexOf("MSIE") != -1) || (!!document.documentMode == true)) {
        document.execCommand('SaveAs', '1', 'page.html');
        event.preventDefault();
    } else {
        if(isChrome) {
            element.setAttribute('href','data:text/html;charset=UTF-8,'+encodeURIComponent('<!doctype html>' + document.documentElement.outerHTML));
        }
        element.setAttribute('download', 'page.html');
    }
}

并在你的锚标签中使用这样的。

<a href="#" onclick="downloadPage(this,event);" download>Download entire page.</a>

示例

    function downloadPage(element, event) {
    	var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
    
    	if ((navigator.userAgent.indexOf("MSIE") != -1) || (!!document.documentMode == true)) {
    		document.execCommand('SaveAs', '1', 'page.html');
    		event.preventDefault();
    	} else {
    		if(isChrome) {
                element.setAttribute('href','data:text/html;charset=UTF-8,'+encodeURIComponent('<!doctype html>' + document.documentElement.outerHTML));
    		}
    		element.setAttribute('download', 'page.html');
    	}
    }
I just need doctype html and should work fine in IE11, Edge and Chrome. 

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

<p>
<a href="#" onclick="downloadPage(this,event);"  download><h2>Download entire page.</h2></a></p>

<p>Some image here</p>

<p><img src="https://placeimg.com/250/150/animals"/></p>

您必须遍历文档childNodes并获取outerHTML内容。

在VBA中看起来像这样

For Each e In document.ChildNodes
    Put ff, , e.outerHTML & vbCrLf
Next e

使用此功能,您可以获取网页的所有元素,包括<!> lt; !DOCTYPE <!> gt;节点是否存在

实际上正确的方法是:

webBrowser1.DocumentText

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top