简体   繁体   中英

Printing in new window in FireFox doesn't work the first time, but afterwards

My script should open a window and trigger the print dialog 2s after that. The script always opens the popup and the print dialog, but the first time it doesn't work to really print (eg to PDF) the document, although it does every other time.

 function PrintElem(elem) { var mywindow = window.open('', 'PRINT', 'height=130px,width=250px'); mywindow.document.write('<html><head>'); mywindow.document.write('</head><body >'); mywindow.document.write(document.getElementById(elem).innerHTML); mywindow.document.write('</body></html>'); mywindow.document.close(); // necessary for IE >= 10 mywindow.focus(); // necessary for IE >= 10*/ setTimeout(function() { mywindow.print(); mywindow.close(); }, 2000) return true; }
 <div id="MyDiv"> <p>Some Text</p> </div> <a id="12345" href="javascript:void(0)" onclick="PrintElem('MyDiv');return false;">Print MyDiv</a>

I think that this line mywindow.document.close(); is causing the issue. It should be after mywindow.document.print();.

Since you now clarified that your script is triggering the window and the print-popup correctly, but only the Printing itself in FF doesn't work as expected the first time, I reasearched a bit.

It's an old closed issue, but there at least is one regarding FF not printing the first time. An comment suggests to delay the close-operation by some time (eg 1s).

It seems you have to delay the close-operation, because otherwise for some reasons FF doesn't know what window to print since it's closed too early. See my plnkr here .

So this is gonna help:

mywindow.print();
setTimeout(function() {
    mywindow.close();
}, 5000)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM