简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM