Javascript 在Chrome中检测浏览器打印事件有两种不同的方式

Javascript 在Chrome中检测浏览器打印事件有两种不同的方式,javascript,google-chrome,printing,Javascript,Google Chrome,Printing,我目前正在使用最新版本的Chrome(43.0.2357.130),从window.print()调用print时,与使用⌘P 使用window.print()打印时,它会正确输出到控制台。当打印对话框打开时,输出打印前的,,当对话框关闭时,输出打印后的 但是,当使用Chrome菜单时,或⌘P要打印,当打印对话框打开时,它会将打印前的和打印后的记录到控制台 下面是我正在使用的代码,它在其他浏览器中运行良好 function beforePrint() { console.log('Bef

我目前正在使用最新版本的Chrome(43.0.2357.130),从
window.print()
调用print时,与使用⌘P

使用
window.print()
打印时,它会正确输出到控制台。当打印对话框打开时,输出打印前的
,当对话框关闭时,输出打印后的

但是,当使用Chrome菜单时,或⌘P要打印,当打印对话框打开时,它会将打印前的
和打印后的
记录到控制台

下面是我正在使用的代码,它在其他浏览器中运行良好

function beforePrint() {
    console.log('Before Print');
}

function afterPrint() {
    console.log('After Print');
}

if (window.matchMedia) {
    var mediaQueryList = window.matchMedia('print');
    mediaQueryList.addListener(function (mql) {
        (mql.matches) ? beforePrint() : afterPrint();
    });
}
else {
    // basically a fallback for < IE11
    window.addEventListener('beforeprint', beforePrint, false);
    window.addEventListener('afterprint', afterPrint, false);
}
这是我使用时得到的输出⌘P或开始打印的菜单:

  Before Print
  After Print
  // Print Dialog is now open, but it is occurring in the wrong place
这是Chrome中的一个bug,还是有其他方法可以正确捕获事件


仅供参考,这里是matchMedia的代码,看起来可能只是Chrome的一个bug

  Before Print
  After Print
  // Print Dialog is now open, but it is occurring in the wrong place