Run javascript when printing a page

when printing the page, it seems that javascript code is executed. How can I determine if a page is currently printing? I am doing some js resizing and should handle printing a little differently.

+8
javascript browser printing
source share
2 answers

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:

<!-- In head --> <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() { // perform changes window.print(); // revert changes } 

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.

+9
source share

AFAIK there is no general possibility. IE has onbeforeprint and onafterprint, which are now also added in Firefox 5/6 + (I donโ€™t know for sure). Consider using custom print styles.

 <link rel="stylesheet" href="print.css" type="text/css" media="print" /> 

Other relevant issues

  • onbeforeprint () and onafterprint () equivalent for non-IE browsers (PHP, MySQL, JavaScript, HTML)
  • Print Trigger Resize Event
  • What event is fired when window.print () is called?
+3
source share

All Articles