How do I print an IFrame from javascript in Safari/Chrome

Andrew Bullock picture Andrew Bullock · Jan 23, 2009 · Viewed 132.2k times · Source

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

Answer

Andrew Bullock picture Andrew Bullock · Jan 23, 2009

Here is my complete, cross browser solution:

In the iframe page:

function printPage() { print(); }

In the main page

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

    iframe.focus();
    ifWin.printPage();
    return false;
}

Update: Many people seem to be having problems with this in versions of IE released since I had this problem. I do not have the time to re-investigate this right now, but, if you are stuck I suggest you read all the comments in this entire thread!