Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Empty html div contents after Window.print()

On button click, I'm using window.print() of javascript for printing print_div contents,

But because of some security issue, i wanted to avoid the multiple printing (like using Cntrl + P) options, So i was thinking of to clear print_div contents, that users can't re-print again and again.

Rough Code here,

document.getElementById("print_div").innerHTML = //Some contents to be printed on paper.
window.print()
document.getElementById("print_div").innerHTML = '' // Clearing old contents to avoid mis-use

But this code not working at all, its clearing print_div contents before creating print preview like in chrome.(i guessed, working Asynchronously)

Could any one tell me, where am doing wrong here?

Note: Am using Chrome: 22.0.1229.92 m to test my code & i want to go for chrome only.

like image 964
Niks Jain Avatar asked Dec 07 '25 14:12

Niks Jain


2 Answers

It's because print window wasn't loaded.

var showPrintWindow = function (context) {
        var printWindow = window.open('', '');
        var doc = printWindow.document;
        doc.write("<html><head>");
        doc.write("<link href='/css/printReport.css' rel='stylesheet' type='text/css' media='print' />");
        doc.write("</head><body>");
        doc.write(context);
        doc.write("</body></html>");
        doc.close();

        function show() {
          if (doc.readyState === "complete") {
              printWindow.focus();
              printWindow.print();
              printWindow.close();
          } else {
              setTimeout(show, 100);
          }
        };
        show();
    };
like image 165
rnofenko Avatar answered Dec 10 '25 03:12

rnofenko


You can use setTimeout method and try it.

setTimeout("your code or function etc",mili seconds)

setTimeout("document.getElementById('print_div').innerHTML = ''",5000);
like image 23
Hkachhia Avatar answered Dec 10 '25 02:12

Hkachhia