views:

112

answers:

2

My site has a "print this page" button.

I load a static print template HTML file into a hidden iframe, copy the HTML into that page using jQuery, and call window.print() from the Iframe page. All is well, except on Safari, which wants to print the parent frame as well, so I get two print dialogs opening.

I've tried calling window.print from within the iframe, and calling it from the parent, targetting the iframe (document.printFrame.window.print()) but I get two dialogs regardless.

Does anyone know a way around this? I only want to print the Iframe, not the parent.

+1  A: 

I can't reproduce the bug; it works fine for me (ie: I get only one Print dialog), regardless of whether I call the it from the iframe or the parent frame. Maybe you are calling window.print() twice somewhere?

I am running Safari 4.0.3 on Mac OS X 10.6

EDIT: Here it is: http://jsfiddle.net/Kq9dc/

EDIT 2: I just tested this on Safari 5.0/Windows 7 and it is working correctly. Are you sure it isn't something else in your code?

EDIT 3: Just tested this on several versions of Safari on WinXP:

Safari 3.0 (first beta): Not working (no print dialog)
Safari 3.1 (first non-beta): Works fine
Safari 4.0: Works fine
Safari 5.0: Works fine
quantumSoup
If I were calling it twice, I would expect the same behaviour on other browsers. Hmmm...
Diodeus
@Diodeus are you getting 2 print dialogs with my [fiddle](http://jsfiddle.net/Kq9dc/)?
quantumSoup
@Diodeus Ran more tests, they seem to be working fine
quantumSoup
I'll post an example when I get some time on Tuesday.
Diodeus
Work deadlines took over my life. Sorry.
Diodeus
A: 

Try this. Put this in said iframe:

function printPage() { print(); }

then in the parent:

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

Should this not work either, I'd try opening up a new window/tab, and fill it with the printable HTML.

var printwin = window.open("about:blank", "_new");
printwin.document.open();
printwin.document.write("HTML goes here..javascript which is going to print is in there too..");
printwin.document.close();

Two minor things to watch out for are

  • split </script> in the new window, so you don't terminate prematurely
  • use setTimeout() to execute after onLoad() has finished, otherwise Firefox users may see a blank page below the print dialog
Michael Foukarakis