js获取window.print()调用打印的回调事件

js获取window.print()调用打印的回调事件

$(function(){
               //定义打印前事件 
                 var beforePrint = function() {
                    console.log("beforePrint");
                }; 
             //定义打印后事件 
                var afterPrint = function() {
                console.log("afterPrint");
                    $("#buttons").show();
                }

              //监听window状态
                if (window.matchMedia) {
                       var mediaQueryList = window.matchMedia('print'); 

                      //为印添加事件
                       mediaQueryList.addListener(function(mql) {
                           if (mql.matches) {
                               beforePrint();
                           } else {
                               afterPrint();
                           }
                       });
                     }

             //打印前事件
                window.onbeforeprint = beforePrint;

             //打印后事件
                window.onafterprint = afterPrint;
                
                $("#print").click(function(){

                     //隐藏页面不需要打印的东西
                       $("#buttons").hide();

                     //执行打印
                    window.print();
                });
            });