Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

override the content of javascript window.print

Tags:

javascript

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.

like image 861
Akash Avatar asked Feb 05 '23 17:02

Akash


2 Answers

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();
};

Working with user driven print events and programmed print events:

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

like image 154
KevBot Avatar answered Feb 10 '23 22:02

KevBot


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'/>
like image 34
I wrestled a bear once. Avatar answered Feb 11 '23 00:02

I wrestled a bear once.