Search code examples
javascripthtml5-canvashtml2canvas

How to resolve the error: Document not attached to a Window?


I am using html2canvas to convert the html to png, I am getting the following 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)
 let htmlString = document.documentElement.innerHTML;
 let virtualDom = new DOMParser().parseFromString(htmlString, "text/html");
 html2canvas(virtualDom.body).then((canvas) => {
       let base64image = canvas.toDataURL("image/png");
      });

If I pass browser DOM it is Ok, but I need new DOM for some reason that's why I use DOMParser. similar question :Link


Solution

  • There is no proper way to do it now. html2canvas relay on window object attached to element. Because html2canvas already allow passing options related to defaultView through options object, the guard which throw error look like a bug because it should check that all necessary options are passed. So it would be better to open an issue there!

    As a workaround if you trust HTML you can try to use hidden iframe but it still should be placed to the document

      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);