window.print() not working in IE

2019-01-03 02:22发布

I am doing something like this in javascript to print a section of my page on click of a link

function printDiv() {
 var divToPrint = document.getElementById('printArea');
 var newWin = window.open();
 newWin.document.write(divToPrint.innerHTML);
 newWin.print();
 newWin.close();
}

It works great in Firefox but not in IE.

Could someone please help

16条回答
beautiful°
2楼-- · 2019-01-03 03:09

Close the window only when it is not IE:

function printDiv() {
 var divToPrint = document.getElementById('printArea');
 var newWin= window.open();
 newWin.document.write(divToPrint.innerHTML);
 newWin.print();
 if (navigator.appName != 'Microsoft Internet Explorer') newWin.window.close();
}
查看更多
【Aperson】
3楼-- · 2019-01-03 03:10

Add these lines after newWin.document.write(divToPrint.innerHTML)

newWin.document.close();
newWin.focus();
newWin.print();
newWin.close();

Then print function will work in all browser...

查看更多
小情绪 Triste *
4楼-- · 2019-01-03 03:11

The way we typically handle printing is to just open the new window with everything in it that needs to be sent to the printer. Then we have the user actually click on their browsers Print button.

This has always been acceptable in the past, and it sidesteps the security restrictions that Chilln is talking about.

查看更多
我想做一个坏孩纸
5楼-- · 2019-01-03 03:11

For Firefox use

iframewin.print()

for IE use

iframedocument.execCommand('print', false, null);

see also Unable to print an iframe on IE using JavaScript, prints parent page instead

查看更多
登录 后发表回答