Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 470
Andrew Bullock Avatar asked Jan 23 '09 13:01

Andrew Bullock


People also ask

How do I print an iframe from Chrome?

Right click within the PDF display area and click print, or use the printer icon within the PDF hover bar. That prints the PDF by itself without the surrounding page. Tested on Chrome 72/Win10. Doing the same outside the iframe will print the rest of the page with a blank box.

How does Window print() work?

The window print() method is used to print the visible contents of the current window, for example, a web page text or image by displaying the Print Dialog Box which allows the user to choose from a variety of printing options, and the Print Dialog Box is only opened when the print() code is executed.


1 Answers

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!

like image 112
Andrew Bullock Avatar answered Sep 21 '22 14:09

Andrew Bullock