How to resolve the error: Document not attached to a Window?
How to resolve the error: Document not attached to a Window?
我正在使用 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. Because html2canvas already allow passing options 通过选项对象与 defaultView 相关,抛出错误的守卫 看起来像一个错误 因为它应该检查所有必要的选项被通过。所以最好在那里开个issue!
作为解决方法,如果您信任 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);
我正在使用 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. Because html2canvas already allow passing options 通过选项对象与 defaultView 相关,抛出错误的守卫 看起来像一个错误 因为它应该检查所有必要的选项被通过。所以最好在那里开个issue!
作为解决方法,如果您信任 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);