Taking a screenshot using Virtual DOM does not work.
Error:
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)
Code:
let htmlString = document.documentElement.innerHTML;
let virtualDom = new DOMParser().parseFromString(htmlString, "text/html");
html2canvas(virtualDom.body).then((canvas) => {
let base64image = canvas.toDataURL("image/png");
});
Specifications:
Any idea?
It's working using iframe
, as suggested by wuyuedefeng in this response on GitHub:
async htmlTextToCanvas(htmlText) { const iframe = document.createElement('iframe'); iframe.style.width = '0px' iframe.style.overflow = 'hidden' document.body.appendChild(iframe) iframe.contentWindow.document.open(); iframe.contentWindow.document.write(htmlText) iframe.contentWindow.document.close() const dom = iframe.contentWindow.document.body //const dom = new DOMParser().parseFromString(`<div>111</div>`, "text/xml").firstChild const canvas = await html2canvas(dom).finally(() => { iframe.parentNode.removeChild(iframe) }) return canvas }