niklasvh / html2canvas

Screenshots with JavaScript
https://html2canvas.hertzen.com/
MIT License
30.11k stars 4.75k forks source link

macOS safari:Unhandled Promise Rejection: Unable to find element in cloned iframe #3102

Closed hktalent closed 11 months ago

hktalent commented 11 months ago

code what happened

function html2img(html) {
    // https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js
    return new Promise(resolve=> {
        const d = document.createElement("div");
        d.innerHTML = html;
        html2canvas(d).then(canvas => {
            canvas.toBlob(blob=>{
                console.log(blog)
                resolve(blob)
            },'image/webp',0.5);
        });
    });
} 

The error message Unhandled Promise Rejection: Unable to find element in cloned iframe means that the JavaScript code is trying to find an element in an iframe, but the element is not there. This can happen for a few reasons:

The element may have been removed from the iframe. The element may not have been loaded yet. The element may be hidden. To troubleshoot this error, you can try the following:

Check the iframe's source code to make sure that the element is still there. Check the iframe's loading status to make sure that it has finished loading. Check the element's visibility to make sure that it is not hidden. If you are still getting the error after checking these things, you may need to debug the JavaScript code to see why it is trying to find an element that is not there.

Here is an example of how to troubleshoot this error:

const iframe = document.getElementById("my-iframe"); const element = iframe.contentDocument.querySelector("#my-element");

if (element === null) { console.error("Unable to find element in cloned iframe"); } This code will first get the iframe element and then get the contentDocument object of the iframe. The contentDocument object is the document that is loaded inside the iframe. Once you have the contentDocument object, you can use it to get the element that you are looking for.

If the element is not there, the code will log an error message. This will help you to determine why the element is not there.