简体   繁体   中英

Add JavaScript and HTML to IFRAME, and print IFRAME to printer

There are multiple posts dealing with part of these topics, but none that puts them together.

On a given page, I wish to create a new IFRAME, add some JavaScript to it which will print the page to a printer, and add some HTML to it which will be printed.

Below is my attempt with a live demo at http://jsbin.com/UDUCADI/2/ . It prints, but prints the parent page and not the IFRAME.

How do I just print the IFRAME?

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>Print IFRAME</title>
        <script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script> 
        <script type="text/javascript">
            $(function () {
                $('#printIt').click(function(){
                    var iframe   = $('<iframe>');
                    var script   = document.createElement("script");
                    script.type  = "text/javascript";
                    script.text  = "window.print()";
                    iframe[0].appendChild(script);
                    iframe.appendTo('body');
                    var iframeDocument=$(iframe[0].contentWindow.document);
                    iframeDocument.find('body').html($('#stuffToPrint').html());
                })
            });
        </script>
    </head>
    <body>
        <button id="printIt">Print</button>
        <div id="stuffToPrint">
            <p>Print this text!</p>
            <img alt="And print this image" src="dropdown_arrow_blue.gif">
        </div>
        <div>Don't print this!</div>
    </body>
</html>

EDITED

There are actually a few things wrong. One of it is you're mixing jQuery and the DOM api. Second would be that you add the script tag to the body of the iframe and then set the HTML of the body again, overwriting the script tag. Third: you're using script.text, which should be script.innerHTML.

$(function () {
$('#printIt').click(function(){
    var iframe   = document.createElement('iframe');
    document.body.appendChild(iframe)
    iframe.contentWindow.document.body.innerHTML = $('#stuffToPrint').html();
    var script   = document.createElement("script");
    script.innerHTML  = "window.print()";
    iframe.contentWindow.document.body.appendChild(script);
})
});

Working version at: http://jsbin.com/UDUCADI/5/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM