2

您好我现在正在使用 Onenote API 发送当前网页的快照:

http://msdn.microsoft.com/en-us/library/office/dn575431(v=office.15).aspx

http://msdn.microsoft.com/en-us/library/office/dn575438(v=office.15).aspx#sectionSection4

发布多部分内容时,我将 HTML 内容放在“MyAppHtmlId”部分:

<img data-render-src="name:MyAppHtmlId" alt="a cool image" width="500"/>

并且 HTML 内容通过以下方式获得:

document.documentElement.outerHTML;

问题是有时保存在 Onenote 中的快照与我在浏览器中看到的不完全相同。但是当我转而使用 Chrome 扩展程序“OneNote Clipper”来测试同一页面时,它运行良好。(示例页面:https ://stackoverflow.com/ )

是我使用了错误的 Javascript 代码来获取 HTML 内容还是我错过了 Onenote API 的其他内容?

4

1 回答 1

0

document.documentElement.outerHTML在将结果发送到服务之前,您需要通过几种方法来修改结果 。

  1. 确保包含 DOCTYPE。如果不包含 DOCTYPE 数据,屏幕截图将以 quirks 模式呈现,这很容易导致屏幕截图不够理想。有一篇文章解释了如何在此处生成正确的 DOCTYPE 字符串:Get DocType of an HTML as string with Javascript我已将他们的代码合并到下面的示例中。

  2. 由于屏幕截图将仅使用 DOM 生成,并且不知道原始 url,因此如果不存在,您将需要添加一个 base 标签。这可确保正确理解用于资源的任何相对路径。

  3. 您可能想要删除任何 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;
}
于 2014-09-19T09:40:51.390 回答