最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Uncaught (in promise) Unable to find element in cloned iframe #2460 - Stack Overflow

programmeradmin0浏览0评论

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:

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

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:

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

Share Improve this question edited Jan 8, 2021 at 16:22 trincot 350k36 gold badges271 silver badges322 bronze badges asked Jan 8, 2021 at 15:52 Raana TashakoriRaana Tashakori 4572 gold badges8 silver badges19 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 14

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.

I encounted the same problem. Finally I solved it like this:

html2canvas(targetElement, options);

->

html2canvas(targetElement.childNodes[0].children, options);

Just do not know why!!!

发布评论

评论列表(0)

  1. 暂无评论