Home >Database >Mysql Tutorial >How to Achieve Cross-Browser Compatibility for `onbeforeprint()` and `onafterprint()`?
Cross-Browser Equivalent for onbeforeprint() and onafterprint()
While IE offers the functionality of onbeforeprint() and onafterprint(), this functionality is not natively supported in all browsers. For a cross-browser solution, consider utilizing window.matchMedia and window.onbeforeprint/window.onafterprint.
Using window.matchMedia
window.matchMedia allows you to detect when a CSS media query becomes active. In the case of printing, the media query 'print' can be used. Add an event listener to the window.matchMedia('print') object to execute a function before and after printing:
if ('matchMedia' in window) { window.matchMedia('print').addListener(function(media) { if (media.matches) { beforePrint(); } else { $(document).one('mouseover', afterPrint); } }); }
Note that this technique may result in multiple calls to beforePrint() and afterPrint(), depending on the browser's behavior.
Using window.onbeforeprint/window.onafterprint
IE and Firefox support the window.onbeforeprint and window.onafterprint events. Listen to these events with jQuery:
$(window).on('beforeprint', beforePrint); $(window).on('afterprint', afterPrint);
Implementation
You can find more information on this cross-browser approach at https://tjvantoll.com/2012/06/15/detecting-print-requests-with-javascript/
The above is the detailed content of How to Achieve Cross-Browser Compatibility for `onbeforeprint()` and `onafterprint()`?. For more information, please follow other related articles on the PHP Chinese website!