'Handle Chrome right click print in Angular

I am creating a project using angular. I want to stop Right click print preview and initialize some code when user click on right click of print.

Here is Code

const mediaQueryPrint = window.matchMedia('print');
    mediaQueryPrint.addListener(this.mediaQueryPrintListener.bind(this));

mediaQueryPrintListener(mql: MediaQueryList) {
    if (mql.matches) {
      // code runs
    }else{
      window.close()
    }
  }

The Problem is print preview is open up, i want to stop print preview.



Solution 1:[1]

It is not possible for your code to stop the functionality of your browser. If someone needs the content on your site, they can even take a screenshot. But however, you can prevent the content of your site from being printed by using media query 'print'.

Ex:

@media print{
   body {
      display: none!important;
      visibility: none!important;
   }
}

This will show a blank screen in print preview. Similary you can play around with that and show your custom message by hiding other content.

Ex:

In HTML
<div id="print-alert">Could not print this page</div>
<div class="not-print"><--YOUR CONTENT--></div>

In CSS
@media screen{
  #print-alert{
    display: none;
  }
}

@media print{
  #print-alert{
    display: block;
  }
  .not-print{
    display: none!important;
    visibility: none!important;
  }
}

This will show the print alert only in print preview and not in actual site. Similary the actual contents are hidden.

Also you can alert the user using javascript window.alert something like this.

ngOnInit(){
  window.onbeforeprint = () =>{
    window.alert("This page could not be printed"); //your message
  }
}

By using this, it will alert the user whenever he tries to use browser print preview.

Solution 2:[2]

Look into QPixmapCache and store your icon in a pixmap instead. Constructing a QIcon from a QPixmap is very straightforward. Look into this QIcon constructor. You may just put the QPixmap in there, since the constructor is implicit anyway. This should speed things up.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 HARI HARAN
Solution 2 aalimian