如何在Safari / Chrome中从javascript打印IFrame

有人可以帮助我在Safari / Chrome中通过JavaScript调用打印IFrame的内容。

这在Firefox中工作:

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

这在IE中工作:

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

但我无法在Safari / Chrome中获得任何东西。

谢谢

安德鲁

把一个打印function放在iframe中,并从父级调用它。

IFRAME:

 function printMe() { window.print() } 

父:

 document.frame1.printMe() 

这是我的完整的跨浏览器解决scheme:

在iframe页面中:

 function printPage() { print(); } 

在主页面

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

更新 :自从我有这个问题以来,很多人似乎在IE的版本中遇到了这个问题。 我没有时间重新调查,现在,如果你卡住了,我build议你读这整个线程中的所有意见!

我使用了Andrew的脚本,但在printPage()函数被调用之前添加了一段。 iframe需要焦点,否则它仍然会在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; } 

不过谢谢你,这是安德鲁写的。 我只是做了一个调整= P

除了安德鲁和马克斯的解决scheme,使用iframe.focus()导致打印父框架,而不是在IE8中只打印子iframe。 修改该行解决了这个问题:

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

使用Firefox的window.frames但也添加name属性,因为它使用Firefox中的iframe

IE:

 window.frames[id] 

火狐:

 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> 

有一件事要注意的是,如果你正在使用file:///在本地进行testing,它将不会在chrome上工作,因为iframe中的函数将显示为undefined。 但是,一旦在Web服务器上,它将工作。

我不得不做一些修改,以使其在IE8(没有与其他IE浏览器风格testing)

1)document.frames [param]似乎接受一个数字,而不是ID

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

2)我有一个打印对话框显示页面加载时,也有一个链接到“点击这里开始打印”(如果它没有自动启动)。 为了得到它的工作,我不得不添加focus()调用

 <script type="text/javascript"> $(function(){ printPage(); }); function printPage() { focus(); print(); } </script> 

您可以使用

 parent.frames['id'].print(); 

在Chrome工作!

你也可以使用

 top.iframeName.print(); 

要么

 parent.iframeName.print(); 

'framePartsList.contentWindow.print();' 在IE 11 ver11.0.43中不工作

因此我用framePartsList.contentWindow.document.execCommand('print',false,null);

用这个:

 window.onload = setTimeout("window.print()", 1000);