Javascript Print iframe contents only

user1083382 picture user1083382 · Mar 8, 2012 · Viewed 205.5k times · Source

This is my code

<script>
var body = "dddddd"    
var script = "<script>window.print();</scr'+'ipt>";

var newWin = $("#printf")[0].contentWindow.document; 
newWin.open();
newWin.close();

$("body",newWin).append(body+script);

</script>
<iframe id="printf"></iframe>

This works but it prints the parent page, how do I get it to print just the iframe?

Answer

mplungjan picture mplungjan · Mar 8, 2012

I would not expect that to work

try instead

window.frames["printf"].focus();
window.frames["printf"].print();

and use

<iframe id="printf" name="printf"></iframe>

Alternatively try good old

var newWin = window.frames["printf"];
newWin.document.write('<body onload="window.print()">dddd</body>');
newWin.document.close();

if jQuery cannot hack it

Live Demo