5

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 ?

zgue
  • 3,417
  • 9
  • 31
  • 35
vaishuani
  • 111
  • 1
  • 2
  • 12

3 Answers3

1

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.

Mohsin Muzawar
  • 956
  • 7
  • 8
1

From MDN

A Window object representing to the newly created window. If the window couldn't be opened, the returned value is instead null. The returned Window reference can be used to access properties and methods of the new window as long as it complies with Same-origin policy security requirements.

If it returned null, it means that the popup window has been blocked by the browser. Perhaps the action has not been initialized by user?

David Votrubec
  • 3,420
  • 1
  • 25
  • 38
1

The simple solution for your fix will be to rename open() function to something else and this will fix your error message.

Copy/Paste in your chrome inspector console.

function print() {
    let 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()">test</body>
      </html>`
    );
    popupWin.document.close();
}
function openOther(){
  //I called Api using service
   let scope=this;
   setTimeout(function() { scope.print(); }, 3000);
}
openOther()

In your case the this is the Window object, using the open name you override the native Window.open function.

LkPark
  • 556
  • 4
  • 12
  • Thanks for ur reply.I also tried to this.But it's not wrk – vaishuani Nov 01 '17 at 11:20
  • Your problem is described here: https://stackoverflow.com/questions/9514698/bypass-popup-blocker-on-window-open-when-jquery-event-preventdefault-is-set In your case if you remove setTimeout this will work – LkPark Nov 01 '17 at 12:38