javascripttypescriptiframe

How to add Html Content to a new created Iframe in JS


I am creating an Iframe and trying to add Html to it's body, butI constantly get an error Cannot read property body of null.

My code looks something like this:

var frameToPrint = document.createElement("IFRAME") as HTMLFrameElement;
frameToPrint.contentDocument.body.innerHTML = "";
It works if I add the Iframe to my HTML and then get it using GetElementById, but I cannot have this Iframe displayed on my page. Even hidden, it messes up my dimensions.

Thank you in advance!


Solution

  • I found the answer. You need to append the new created frame to your body. That initializes the contentWindow and the contentDocument of the iframe.

    var frameToPrint = document.createElement("iframe");
    frameToPrint.setAttribute("name", "prnt");
    document.body.appendChild(frameToPrint);