window.print () не работает в IE - PullRequest
62 голосов
/ 31 марта 2010

Я делаю что-то вроде этого в javascript, чтобы напечатать раздел моей страницы при нажатии на ссылку

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

Отлично работает в Firefox, но не в IE.

Может кто-нибудь, пожалуйста, помогите

Ответы [ 16 ]

129 голосов
/ 18 мая 2011

Добавьте эти строки после newWin.document.write(divToPrint.innerHTML)

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

Тогда функция печати будет работать во всех браузерах ...

10 голосов
/ 27 июня 2014

Добавить newWin.document.close (); , вот так:

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

Это делает IE счастливым. НТН, -Ted

8 голосов
/ 15 июня 2012
function printDiv() {
    var divToPrint = document.getElementById('printArea');
    newWin= window.open();
    newWin.document.write(divToPrint.innerHTML);
    newWin.location.reload();
    newWin.focus();
    newWin.print();
    newWin.close();
}
4 голосов
/ 02 сентября 2011

У меня была такая проблема раньше, и решение состоит в том, чтобы просто вызывать window.print () в IE, а не вызывать print из экземпляра окна:

function printPage(htmlPage)
    {
        var w = window.open("about:blank");
        w.document.write(htmlPage);
        if (navigator.appName == 'Microsoft Internet Explorer') window.print();
        else w.print();
    }
3 голосов
/ 08 апреля 2017
<!DOCTYPE html>
<html>
<head id="head">
<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE" /> 
  <!-- saved from url=(0023)http://www.contoso.com/ -->
  <link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div>
  <div>
    Do not print
  </div>
  <div id="printable" style="background-color: pink">
    Print this div
  </div>
  <button onClick="printdiv();">Print Div</button>
</div>
</body>
<script>
  function printdiv()
    {
  var printContents = document.getElementById("printable").innerHTML;
  var head = document.getElementById("head").innerHTML;
  //var popupWin = window.open('', '_blank');
  var popupWin = window.open('print.html', 'blank');
  popupWin.document.open();
  popupWin.document.write(''+ '<html>'+'<head>'+head+'</head>'+'<body onload="window.print()">' + '<div id="printable">' + printContents + '</div>'+'</body>'+'</html>');
  popupWin.document.close();
 return false;
};
</script>
</html>
3 голосов
/ 04 декабря 2015

добавить условие проверки для нагрузки

if (newWinObj.onload) {
    newWinObj.onload = function() {
        newWinObj.print();
        newWinObj.close();
    };
}
else {
    newWinObj.print();
    newWinObj.close();
}
3 голосов
/ 03 февраля 2012

Просто подождите немного, прежде чем закрыть окно!

if (navigator.appName != 'Microsoft Internet Explorer') {
    newWin.close();
} else {
    window.setTimeout(function() {newWin.close()}, 3000);
}
2 голосов
/ 28 марта 2017

Просто чтобы добавить дополнительную информацию.В IE 11 использование только

window.open() 

приводит к неопределенности

window.document

.Чтобы решить эту проблему, используйте

window.open( null, '_blank' )

. Это также будет правильно работать в Chrome, Firefox и Safari.

У меня недостаточно репутации, чтобы комментировать, поэтому пришлось создать ответ.

2 голосов
/ 25 октября 2016

Для использования Firefox

iframewin.print()

для использования IE

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

см. Также Невозможно распечатать iframe в IE с использованием JavaScript, вместо этого печатается родительская страница

2 голосов
/ 03 февраля 2016

У меня это сработало, работает в Firefox, т.е. и в Chrome.

    var content = "This is a test Message";

    var contentHtml = [
        '<div><b>',
        'TestReport',
        '<button style="float:right; margin-right:10px;"',
        'id="printButton" onclick="printDocument()">Print</button></div>',
        content
    ].join('');

    var printWindow = window.open();

    printWindow.document.write('<!DOCTYPE HTML><html><head<title>Reports</title>',
        '<script>function printDocument() {',
        'window.focus();',
        'window.print();',
        'window.close();',
        '}',
        '</script>');

    printWindow.document.write("stylesheet link here");

    printWindow.document.write('</head><body>');
    printWindow.document.write(contentHtml);
    printWindow.document.write('</body>');
    printWindow.document.write('</html>');
    printWindow.document.close();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...