Onbeforeprint and onafterprint not working in Chrome and IE?

I use print in my project (using HTML and javascript). In mozilla, onbeforeprint and onafterprint work correctly, but do not work in chrome.

+6
source share
5 answers

What works in Chrome, you need to check "matchmedia" in the "window", as in:

if ('matchMedia' in window) { window.matchMedia('print').addListener(function (media) { //do before-printing stuff }); } else { window.onbeforeprint = function () { //do before-printing stuff } } 
+9
source

Chrome does not have onbeforeprint.

The preferred way to do this is to use special print styles for printing .

If you absolutely need to detect print operations with the javascript cross browser , this looks promising, but I haven't tried it myself.

+1
source

Chrome does not support these events. Instead, it supports window.matchMedia . There is also a bug in Chrome that prevents it from printing all pages. For this reason, I suggest you add a print button to your web page and ask users to use the button instead of printing through the Chrome menu.

 var beforePrint = function() { console.log("before"); }; var afterPrint = function() { console.log("after"); }; var launchedFromMenu = true; if (window.matchMedia) { var mediaQueryList = window.matchMedia('print'); mediaQueryList.addListener(function(mql) { if (mql.matches) { if(launchedFromMenu) { // https://bugs.chromium.org/p/chromium/issues/detail?id=571070 alert("There is a bug in Chrome/Opera and printing via the main menu does not work properly. Please use the 'print' icon on the page."); } beforePrint(); } else { afterPrint(); } }); } // These are for Firefox window.onbeforeprint = beforePrint; window.onafterprint = afterPrint; function printPage() { window["beforePrint"](); launchedFromMenu = false; window.print(); } 
+1
source

Quick update as support for print events has improved significantly

  • Chrome 63, released in December 2017, supports its source
  • Opera 50 also
  • Edge supports it from the start
  • even the old version 6 of IE (6 !!) supports it
0
source

Onbeforeprint and onAfterPrint do not work in Chrome.

But you can restrict printing to page using css print media

Example

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

This css is included in the page title.

css having the following styles

 #header, #menu, #entry-content, .noprint {display: none;} 
-1
source

All Articles