在JS中是否有一种方法可以在HTML标签中获取整个HTML,作为字符串?

document.documentElement.??

当前回答

你还可以:

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

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

其他回答

我只需要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>

document.documentElement.innerHTML

正确的做法其实是:

webBrowser1。DocumentText

我总是用

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

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

使用document.documentElement。

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