Skip to content

Instantly share code, notes, and snippets.

@shaliko
Created November 19, 2012 14:05
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save shaliko/4110822 to your computer and use it in GitHub Desktop.
Save shaliko/4110822 to your computer and use it in GitHub Desktop.
Cross browser print request detection (IE 5+, Firefox 6+, Chrome 9+, and Safari 5.1+ )
(function() {
var beforePrint = function() {
console.log('Functionality to run before printing.');
};
var afterPrint = function() {
console.log('Functionality to run after printing');
};
if (window.matchMedia) {
var mediaQueryList = window.matchMedia('print');
mediaQueryList.addListener(function(mql) {
if (mql.matches) {
beforePrint();
} else {
afterPrint();
}
});
}
window.onbeforeprint = beforePrint;
window.onafterprint = afterPrint;
}());
@bartonlp
Copy link

Well not quite. On Chrome Version 33.0.1750.117 under Linux Mint 15 at least it does not work 100%. If you right click 'print' it works OK but window.print() doesn't work at all. I hate browsers! Why can't we just have one. I would even be willing to live with Internet Explorer if it was the only one -- well maybe not!

@tsukasa-mixer
Copy link

$.fn.beforeprint = function(callback) {
    return $(this).each(function() {
        if ( !jQuery.isWindow(this) )
            return;
        if ( this.onbeforeprint !== undefined )
            $(this).on('beforeprint', callback);
        else if ( this.matchMedia )
            this.matchMedia('print').addListener(callback);
    });
};
$.fn.afterprint = function(callback) {
    return $(this).each(function() {
        if ( !jQuery.isWindow(this) )
            return;
        if ( this.onafterprint !== undefined )
            $(this).on('afterprint', callback);
        else if ( this.matchMedia )
            $(this).one('mouseover', callback);
    });
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment