javascript - 如何解决错误: Document not attached to a Window?

标签 javascript html5-canvas html2canvas

我正在使用html2canvas要将 html 转换为 png,我收到以下错误:

html2canvas.min.js:20 Uncaught (in promise) Error: Document is not attached to a Window
    at html2canvas.min.js:20:193237
    at html2canvas.min.js:20:1976
    at Object.next (html2canvas.min.js:20:2081)
    at html2canvas.min.js:20:1023
    at new Promise (<anonymous>)
    at a (html2canvas.min.js:20:774)
    at Vs (html2canvas.min.js:20:192912)
    at html2canvas.min.js:20:196186
    at takeScreenShot (set style [modal].html:94:7)
    at action (set style [modal].html:68:11)
 let htmlString = document.documentElement.innerHTML;
 let virtualDom = new DOMParser().parseFromString(htmlString, "text/html");
 html2canvas(virtualDom.body).then((canvas) => {
       let base64image = canvas.toDataURL("image/png");
      });

如果我传递浏览器 DOM,那就没问题,但由于某种原因我需要新的 DOM,这就是我使用 DOMParser 的原因。 类似的问题:Link

最佳答案

现在没有合适的方法来做到这一点。 html2canvas relay on window object attached to element 。因为 html2canvas 已经允许 passing options通过选项对象与defaultView相关,抛出错误看起来像一个错误的守卫,因为它应该检查是否传递了所有必要的选项。所以最好在那里打开一个问题!

作为一种解决方法,如果您信任 HTML,您可以尝试使用隐藏的 iframe,但它仍然应该放置在文档中

  const html = "<div>Hello World!</div>";
  const iframe = document.createElement("iframe");
  document.body.appendChild(iframe); // 👈 still required
  iframe.contentWindow.document.open();
  iframe.contentWindow.document.write(html);
  iframe.contentWindow.document.close();
  html2canvas(iframe.contentWindow.document.body);

关于javascript - 如何解决错误: Document not attached to a Window?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70644799/

相关文章:

javascript - 用于嵌套字段的 Formik 字段数组

javascript - 单击父路线时保持子路线相同

html - 如何并排对齐多个饼图?

javascript - 如何使用 Javascript 截取 GMaps Frame 的屏幕截图并将其转换为图像?

javascript - 如何让 html2canvas 在 ie8 中工作?

javascript - React Native "TypeError: Object(...) is not a function" react 导航堆栈错误

javascript - 通过ajax过滤列表并请求数据

javascript - 在 Canvas 上绘制多个正方形

javascript - Canvas 上的抗锯齿文本

javascript - html2canvas.js 不捕获动态生成的内容的图像