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条回答
爷的心禁止访问
2楼-- · 2019-01-03 02:44

Just wait some time before closing the window!

if (navigator.appName != 'Microsoft Internet Explorer') {
    newWin.close();
} else {
    window.setTimeout(function() {newWin.close()}, 3000);
}
查看更多
神经病院院长
3楼-- · 2019-01-03 02:46

add checking condition for onload

if (newWinObj.onload) {
    newWinObj.onload = function() {
        newWinObj.print();
        newWinObj.close();
    };
}
else {
    newWinObj.print();
    newWinObj.close();
}
查看更多
狗以群分
4楼-- · 2019-01-03 02:46
function functionname() {

    var divToPrint = document.getElementById('divid');
    newWin= window.open();
    newWin.document.write(divToPrint.innerHTML);
    newWin.location.reload();
    newWin.focus();
    newWin.print();
    newWin.close();
}
查看更多
地球回转人心会变
5楼-- · 2019-01-03 02:51

I am not sure but i think it occurs because of the security rules of the InternetExplorer...

If you call a function like print() it asks the user manually if he wants to permit active scripting, if he clicks on the yellow bar and selects 'Yes', the print dialog appears. If you click 'No' or just don't do anything it is not executing the parts which are considered as active scripting or other security relevant javascript functions.

In your example the window is opened then print() is called, confirmation bar pops up (nothing is selected, in fact nothing can be selected due to the short time), newWin.close() is called, window closes.

You should try adding the page to the trusted sites in InternetExplorer or change security settings.

There may be a way of handling the security policies in the javascript itself but i don't know much about InternetExplorer Security Policies.

Hope this helps

查看更多
贪生不怕死
6楼-- · 2019-01-03 02:56

Add newWin.document.close();, like so:

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

This makes IE happy. HTH, -Ted

查看更多
放荡不羁爱自由
7楼-- · 2019-01-03 02:56

Just to add some additional information. In IE 11, using merely

window.open() 

causes

window.document

to be undefined. To resolve this, use

window.open( null, '_blank' )

This will also work correctly in Chrome, Firefox and Safari.

I don't have enough reputation to comment, so had to create an answer.

查看更多
登录 后发表回答