purazumakoiの[はてなブログ]

技術メモから最近はライフログも増えてきてます。

javascriptでブラウザの印刷イベントの実行前、実行後を取る

IEのみバージョン5以降

window.onbeforeprint = function() {
    console.log('This will be called before the user prints.');
};
window.onafterprint = function() {
    console.log('This will be called after the user prints');
};

Firefoxjquery読み込み)

(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;
}());

Chrome

Firefoxと同じコードでafterPrintのほうが実行される