How do I print an IFrame from javascript in Safari

2019-01-02 15:09发布

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

11条回答
一个人的天荒地老
2楼-- · 2019-01-02 15:37

I had to make few modifications in order to make it with in IE8 (didn't test with other IE flavours)

1) document.frames[param] seem to accept a number, not 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) I had a print dialog displayed upon page load and also there was a link to "Click here to start printing" (if it didn't start automatically). In order to get it work I had to add focus() call

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

  function printPage()
  {
    focus();
    print();
  }
</script>
查看更多
美炸的是我
3楼-- · 2019-01-02 15:37

You can also use

top.iframeName.print();

or

parent.iframeName.print();
查看更多
泪湿衣
4楼-- · 2019-01-02 15:38

Use firefox window.frames but also add the name property because that uses the iframe in 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>
查看更多
浪荡孟婆
5楼-- · 2019-01-02 15:41

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

iframe:

function printMe() {
  window.print()
}

parent:

document.frame1.printMe()
查看更多
时光乱了年华
6楼-- · 2019-01-02 15:46

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 dont have time to-reinvestigate right now, if youre stuck i suggest you read all the comments in this whole thread!

查看更多
浪荡孟婆
7楼-- · 2019-01-02 15:50

The 'framePartsList.contentWindow.print();' was not working in IE 11 ver11.0.43

Therefore I have used framePartsList.contentWindow.document.execCommand('print', false, null);

查看更多
登录 后发表回答