Search code examples
html2canvas

Taking a screenshot using Virtual DOM does not work


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:

  1. html2canvas version tested with: html2canvas 1.4.0
  2. Browser & version: Google Chrome & Version 96.0.4664.110 (Official Build) (64-bit)

Any idea?


Solution

  • 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
      }