views:

12504

answers:

5

Hi,

Can someone please help me out with printing the contents of an IFrame via a javascript call in Safari/Chrome.

This works in firefox:

$('#' + id)[0].focus();
$('#' + id)[0].contentWindow.print();

this works in IE:

window.frames[id].focus();
window.frames[id].print();

But I can't get anything to work in Safari/Chrome.

Thanks

Andrew

+4  A: 

Put a print function in the iframe and call it from the parent.

iframe:

function printMe() {
  window.print()
}

parent:

document.frame1.printMe()
Diodeus
Good plan, batman!
Andrew Bullock
How did you get document.frame1 to work? I had to use this instead: document.getElementById('frame1').contentWindow.printMe()
Andres Jaan Tack
Use the NAME property, not the ID.
Diodeus
It is not working in IE8.It is printing all the contents (outside of iframe also).Any idea please..
BlackPanther
Check your print settings. The browser controls this, not the page.
Diodeus
+8  A: 

here is my complete, cross browser solution:

in the iframe page:

function printPage() { print(); }

in the pain page

function printIframe(id)
{
    var iframe = document.frames ? document.frames[id] : document.getElementById(id);
    var ifWin = iframe.contentWindow || iframe;
    ifWin.printPage();
    return false;
}
Andrew Bullock
Thanks for this script Andrew. However you did leave one piece out that makes it work in IE 8. Please see my post below
Max Felker
bah bloody ie!!
Andrew Bullock
+1  A: 

it appears this approach is not cross browser compliant. :(

Does not work in Opera 10.01 1844 and Chrome 3.0.195.33

I did a simple test with an html file using this code and both Opera and Chrome print out the entire page (not just the iframe). I called the function from both the parent window and from inside the iFrame calling the parent script.

any thoughts on why this could be happening?

nwilcox
+3  A: 

I used Andrew's script but added a piece before the printPage() function is called. The iframe needs focus, otherwise it will still print the parent frame in IE.

function printIframe(id)
{
    var iframe = document.frames ? document.frames[id] : document.getElementById(id);
    var ifWin = iframe.contentWindow || iframe;
    iframe.focus();
    ifWin.printPage();
    return false;
}

Don't thank me though, it was Andrew who wrote this. I just made a tweak =P

Max Felker
A: 

Para firefox tambien utilicen window.frames pero agreguen la propiedad name al iframe porque ese utiliza firefox

IE: window.frames[id]

Firefox: window.frames[name]

<img src="print.gif"  onClick="javascript: window.frames['factura'].focus(); parent['factura'].print();">
<iframe src="factura.html" width="100%" height="400" id="factura" name="factura"></iframe>
Luis Garcia
easy for you to say
Andrew Bullock