'How to trigger javascript on print event?
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 library is great for screen but not for print.
Any idea how to achieve this?
Solution 1:[1]
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).
Solution 2:[2]
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
Solution 3:[3]
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!
Solution 4:[4]
I have implemented for disabling printing using window.onbeforeprint()
/*Block printing*/
window.onbeforeprint = (event) => {
console.log("onbeforeprint function");
printDiabled();
};
function printDiabled() {
var headstr = " <span style='font-size: large; font - weight: bold; color: Red''>PRINT IS DISABLED</span>";
//var oldstr = document.body.innerHTML;
document.body.innerHTML = headstr;
}
/*Block printing*/
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 | user229044 |
| Solution 2 | Ajay Beniwal |
| Solution 3 | Ed Wade |
| Solution 4 | Ashi |
