Copy the contents of the div into a new iframe
P粉042455250
P粉042455250 2023-08-17 17:03:59
0
1
404
<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粉042455250
P粉042455250

reply all(1)
P粉306523969

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();
        });
    };
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!