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:54

In addition to Andrew's and Max's solutions, using iframe.focus() resulted in printing parent frame instead of printing only child iframe in IE8. Changing that line fixed it:

function printIframe(id)
{
    var iframe = document.frames ? document.frames[id] : document.getElementById(id);
    var ifWin = iframe.contentWindow || iframe;
    ifWin.focus();
    ifWin.printPage();
    return false;
}
查看更多
呛了眼睛熬了心
3楼-- · 2019-01-02 15:54

You can use

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

Work at Chrome!

查看更多
栀子花@的思念
4楼-- · 2019-01-02 15:58

One thing to note is if you are testing this locally using file:///, it will not work on chrome as the function in the iframe will appear as undefined. However once on a web server it will work.

查看更多
十年一品温如言
5楼-- · 2019-01-02 15:59

I used Andrew's script but added a piece before the printPage() function is called. The iframe needs focus, otherwise it will still print the parent frame in 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;
}

Don't thank me though, it was Andrew who wrote this. I just made a tweak =P

查看更多
呛了眼睛熬了心
6楼-- · 2019-01-02 16:02

Use this:

window.onload = setTimeout("window.print()", 1000);
查看更多
登录 后发表回答