Is it possible to trigger a javascript event when a user prints a page? I would like to remove a dependancy on a javascript library, when a user opts to print a page, as the
It can be done by overwriting, e.g., window.onbeforeprint
.
Using Chrome, I found that the more arcane window.matchMedia("print").addListener(function() {alert("Print Dialog open.")})
also works.
This debatable feature can be used in order to deter users from printing a page.
I've encountered it the first time on Scribd. There, if you open the print dialog using the menu command, the page content will be greyed out and a warning pop-over message appears explaining why you can not print the page. (Note for complete analysis: on that page, control-p is also overriden so you can not use it to open the print dialog at all. Additionally, there is a @media CSS for printer output that hides the content; all tested on Firefox).
if you have a scenario where u want to do something before print dialog appears or just after the document is sent to printer queue use can use the below events window.onafterprint , window.onbeforeprint
For anyone stumbling upon this answer from Google, let me try to clear things up:
As Ajay pointed out, there are two events which are fired for printing, but they are not well-supported; as far as I have read, they are only supported in Internet Explorer and Firefox (6+) browsers. Those events are window.onbeforeprint and window.onafterprint, which (as you'd expect) will fire before and after the print job.
However, as pointed out in Joe's link (https://stackoverflow.com/a/9920784/578667), that's not exactly how it is implemented in all cases. In most cases, both events fire before the dialog; in others, script execution might be halted during the print dialog, so both events may fire at the same time (after the dialog has been completed).
For more information (and browser support) for these two events:
https://developer.mozilla.org/en-US/docs/DOM/window.onbeforeprint
https://developer.mozilla.org/en-US/docs/DOM/window.onafterprint
The short answer: if you're hoping to interfere with the print flow, don't. If you're hoping to trigger code after printing, it's not going to work how you're wanting; expect poor browser support, and try to degrade gracefully.
For anyone coming here looking for an option using Bootstrap as I was, I used the following code to achieve this when a print button is clicked. This won't work when they press CTRL + P.
$("#print_page").click(function(){
$("#print_section").addClass('visible-print-block');
window.print();
$("#print_section").removeClass('visible-print-block');})
You need to add hidden-print to anything you don't want printed and then add an ID (or a class if you have more than one section) of print_section to the bit you want printed! Bit hacky but it works!