document.documentElement.outerHTML
在将结果发送到服务之前,您需要通过几种方法来修改结果 。
确保包含 DOCTYPE。如果不包含 DOCTYPE 数据,屏幕截图将以 quirks 模式呈现,这很容易导致屏幕截图不够理想。有一篇文章解释了如何在此处生成正确的 DOCTYPE 字符串:Get DocType of an HTML as string with Javascript我已将他们的代码合并到下面的示例中。
由于屏幕截图将仅使用 DOM 生成,并且不知道原始 url,因此如果不存在,您将需要添加一个 base 标签。这可确保正确理解用于资源的任何相对路径。
您可能想要删除任何 noscript 标签。由于您的有效负载将在不运行 Javascript 的情况下呈现,因此将呈现任何存在的 noscript 标签,这可能会导致您的屏幕截图中出现不需要的内容。
下面是一些示例代码,它们应该在最大限度地减少当前页面 DOM 上的更改的同时处理这些目标:
function getDom() {
// Get the DOCTYPE
var node = document.doctype;
var doctype = "<!DOCTYPE "
+ node.name
+ (node.publicId ? ' PUBLIC "' + node.publicId + '"' : '')
+ (!node.publicId && node.systemId ? ' SYSTEM' : '')
+ (node.systemId ? ' "' + node.systemId + '"' : '')
+ '>';
// Before we get the document's outerHTML, create a base tag if one doesn't exist
if (!document.getElementsByTagName('base').length) {
var baseUrl = document.location.href;
baseUrl = baseUrl.substr(0, baseUrl.lastIndexOf('/') + 1);
var base = document.createElement('base');
base.href = baseUrl;
// The base tag is the first child of head to ensure we don't misload links/scripts in the head
document.head.insertBefore(base, document.head.firstChild);
}
// Store the outerHTML with DOCTYPE
var html = doctype + document.documentElement.outerHTML;
// Remove the text for any noscript elements from html
var noscriptElements = document.getElementsByTagName('noscript');
for (var i = 0; i < noscriptElements.length; i++) {
html = html.replace(noscriptElements[i].outerHTML, '');
}
return html;
}