I want to override the behavior of window.print, like if the dom contains a table I don't want certain rows to be printed.
I referred to the below stack overflow answer on how to hack the javacript event, but not sure how I can update the dom content for the print JavaScript: Overriding alert()
Can anyone throw some light into this.
Thanks.
You can run your own special JavaScript by overriding the window.print
function. However, this is a different flow than someone clicking print from the navigation bar.
window.print
is the print flow as launched by the application.
var oldPrintFunction = window.print;
window.print = function () {
console.log('Gonna do some special stuff');
oldPrintFunction();
};
I had to go look this up as I had something I wrote a long time ago that did something similar, and it seems that I found it. This code watches for the media change to go to print
.
function beforePrint() {
console.log('Do something special before print');
}
function afterPrint() {
console.log('Do something after print');
}
if (window.matchMedia) {
window.matchMedia('print').addListener(function (mql) {
if (mql.matches) {
beforePrint();
}
else {
afterPrint();
}
});
}
// For IE, does not attach in browsers that do not support these events
window.addEventListener('beforeprint', beforePrint, false);
window.addEventListener('afterprint', afterPrint, false);
This will run whatever is in the beforePrint
function for calling window.print()
, or the user chooses to print using a browser flow (command+p, file->print), etc.
Please note: The afterprint
has a bug in Chrome, see my StackOverflow question here
use media queries to add styles that will only be applied to the printed version of the page...
@media print {
#idOdTableNotToPrint{ display:none; }
}
This will hide the table with id of idOdTableNotToPrint
only when the page is printed.
Or if you want to create a whole new stylesheet for it, you can specify that the CSS is for print only in the <link>
tag by adding a media='print'
attribute:
<link rel="stylesheet" href="css/print_styles.css" media='print'/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With