javascriptreactjstypescripthtml5-canvashtml2canvas

Uncaught (in promise) Unable to find element in cloned iframe #2460


How can I fix this error?

My code:

const wrapper = document.createElement("div");
const myHTMLString = "<div>Hello</div>";
wrapper.insertAdjacentHTML("afterbegin",myHTMLString);
//console.log(">>>",wrapper);
html2canvas(wrapper,{useCORS: true}).then((canvas) => {
    wrapper.appendChild(canvas); 
    console.log("canvas>>",wrapper.appendChild(canvas));
    var base64encodedstring = canvas.toDataURL('image/jpeg', 1.0);
    console.log("base6", base64encodedstring );
});

Error:

enter image description here

176e275da87 1ms Starting document clone
Uncaught (in promise) Unable to find element in cloned iframe


Solution

  • The html2canvas documentation says (I highlight in bold):

    The script allows you to take "screenshots" of webpages or parts of it, directly on the users browser. The screenshot is based on the DOM [...]

    The script traverses through the DOM of the page it is loaded on. It gathers information on all the elements there, which it then uses to build a representation of the page. In other words, it does not actually take a screenshot of the page, but builds a representation of it based on the properties it reads from the DOM.

    This all means that the argument you pass to html2canvas must be an element that is present in the document. This explains the (uncaught) error you got:

    Unable to find element in cloned iframe

    Apparently this tool creates a temporary iframe in which it clones the document. Then it will search the element you passed as argument. Since in your case wrapped is not part of the document, this search fails.

    So before calling html2canvas you could do:

     document.body.appendChild(wrapper);
    

    And then if you don't want it to stay in the DOM, remove it again as soon as you have the canvas rendering.