search

Home  >  Q&A  >  body text

Copy the contents of the div into a new iframe

<p>Ultimately I'm trying a technique that prints a specific <code>div</code> but I'm stuck on this part of the question. </p> <p>I have some code that should be copied from a <code>div</code> to a new <code>iframe</code>: </p> <pre class="brush:js;toolbar:false;">var iframe = document.createElement('iframe'); var div = document.querySelector('div#sidebar'); var content = div.innerHTML; iframe.srcdoc = `<!DOCTYPE html><html><head></head><body>${content}</body></html>`; document.body.append(iframe); iframe.contentWindow.print(); </pre> <p>I tried this in the developer tools on the SO page (I could try using <code>div#sidebar</code>). </p> <p>I noticed that I need to add <code>iframe</code> to the document for this to work. Otherwise, the <code>.contentWindow</code> property is <code>null</code>. </p> The <p>code seems to work to some extent, but the <code>iframe</code> is empty, or appears to be empty. The final printout is blank. </p> <p>Any tips in creating a new <code>iframe</code> with copied content? </p>
P粉042455250P粉042455250548 days ago460

reply all(1)I'll reply

  • P粉306523969

    P粉3065239692023-08-18 12:19:00

    Okay, I have an answer. I should know better as I just finished teaching a similar topic.

    The code is valid, but it runs too early. I need to wait for the document to finish loading.

    This is a working version:

    var iframe = document.createElement('iframe');
    var div = document.querySelector('div#sidebar');
    var content = div.innerHTML;
    iframe.srcdoc = `<!DOCTYPE html><html><head></head><body>${content}</body></html>`;
    
    document.body.append(iframe);
    
    //  等待iframe加载完成:
        iframe.onload = () => {
            iframe.contentWindow.print();
            iframe.contentWindow.addEventListener('afterprint', event => {
                iframe.remove();
            });
        };
    

    reply
    0
  • Cancelreply