onbeforeprint和onafterprint在Chrome和IE中不起作用?

Sha*_*her 8 javascript html5

我在我的项目中使用打印(使用HTML和javascript).在mozilla onbeforeprint和onafterprint工作正常但没有使用chrome.

小智 10

对Chrome有用的是检查'window'中的'matchmedia',如下所示:

                if ('matchMedia' in window) {
                    window.matchMedia('print').addListener(function (media) {
                    //do before-printing stuff
                    });
                } else {
                    window.onbeforeprint = function () {
                    //do before-printing stuff
                    }
                }
Run Code Online (Sandbox Code Playgroud)

  • 在打印文档时(使用addListener),侦听器似乎被触发了两次.除了时间戳之外,媒体论点似乎在这两个电话中没有太大差别...... (2认同)
  • media.matches在打印前将为"true",之后为false. (2认同)

Rya*_*yan 1

Chrome 没有 onbeforeprint。

执行此操作的首选方法是使用印刷媒体特定的样式表

如果您绝对必须使用 javascript 跨浏览器检测打印操作,这看起来很有希望,但我自己还没有尝试过。

2021 更新:它从chrome 版本 63开始工作