Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot read property 'document' of null when try to print html document

I am using angualr 2.

I am trying to print html div.

here is my code

<div id="print-section">
  // Html code
</div>
<button (click)="open()">print</button>

 print(): void {
    let printContents, popupWin;
    printContents = document.getElementById('print-section').innerHTML;
    popupWin = window.open('', '_blank', 'top=0,left=0,height=100%,width=auto');
    popupWin.document.open();
    popupWin.document.write(`
      <html>
        <head>
          <title>Print tab</title>
         </head>
    <body onload="window.print();window.close()">${printContents}</body>
      </html>`
    );
    popupWin.document.close();
}

here is my open()

open(){
  //I called Api using service
   let scope=this;
   setTimeout(function() { scope.print(); }, 3000);
}

But i am getting this err

ERROR TypeError: Cannot read property 'document' of null.

How can i fix this issue ?

like image 429
vaishuani Avatar asked Nov 01 '17 10:11

vaishuani


1 Answers

It is blocked by the browser. window.open is only not being blocked, when it is invoked by user action, for example in a click event, emitted by a native browser event.

like image 148
Mohsin Muzawar Avatar answered Oct 05 '22 22:10

Mohsin Muzawar