You cannot except IE browsers. No other browser has a print event before. However, you can target a specific stylesheet, which applies only during printing:
<link rel="stylesheet" type="text/css" media="print" href="print.css" />
This style sheet will be applied before printing. This allows you to make some amazing changes, including hiding the main sections, moving objects, and performing a print-only style, such as page breaks.
Another option is to provide the user with the "Print this page" button. This button can process your JavaScript, call window.print() and return the changes:
function printMe() {
The window.print() method always blocks (in every browser I tested), so itโs safe to immediately return changes after that. However, if the user selects printing through a menu or toolbar, you're out of luck.
One way to handle this case in a complex web application was to have a print stylesheet that hid everything except the special DIV. If the user clicked print, they would receive a warning message. If they clicked the print button, then this div will be filled with the correct information. It's not great, but at least they didn't get a few pages of garbage.
Overzealous
source share