onbeforeprint()和onafterprint()等效于非IE浏览器

ubi*_*con 18 html javascript php mysql onbeforeprint

当用户打印某个网页时,我想将一些信息发送回我的数据库.我可以在IE中使用onbeforeprint()onafterprint()我这样做,但我想以浏览器不可知的方式做同样的事情.只要它完成,就不关心我必须使用哪种技术组合(PHP,MySQL,JavaScript,HTML).有任何想法吗?

编辑:

还有一些问题.我尝试将我的功能放在我Print.css的图像中,但我正在弄乱它的一些方法.然后我尝试添加一个事件监听器,但我也无法让它正常工作.如果有人能提供一些关于如何在任何浏览器中打印前调用函数的更多细节,我将不胜感激.

编辑:

我现在正在放弃这个,我已经采取了另一种做我想做的方式.我期待着FireFox支持onbeforeprint()和onafterprint()的那一天.

qui*_*int 32

许多浏览器现在支持window.matchMedia.此API允许您检测CSS媒体查询何时生效(例如,旋转屏幕或打印文档).对于跨浏览器方法,请window.matchMediawindow.onbeforeprint/ 结合使用window.onafterprint.

以下内容可能导致多次调用beforePrint()afterPrint()(例如,每次重新生成打印预览时,Chrome都会触发侦听器).这取决于您为响应打印而执行的特定处理,这可能是也可能不合适.

if ('matchMedia' in window) {
    // Chrome, Firefox, and IE 10 support mediaMatch listeners
    window.matchMedia('print').addListener(function(media) {
        if (media.matches) {
            beforePrint();
        } else {
            // Fires immediately, so wait for the first mouse movement
            $(document).one('mouseover', afterPrint);
        }
    });
} else {
    // IE and Firefox fire before/after events
    $(window).on('beforeprint', beforePrint);
    $(window).on('afterprint', afterPrint);
}
Run Code Online (Sandbox Code Playgroud)

更多:http://tjvantoll.com/2012/06/15/detecting-print-requests-with-javascript/

  • 值得注意的是,Chrome似乎两次打印此事件. (3认同)

Wri*_*ken 6

不确定其他浏览器会允许你这样做.你当然可以在打印样式表中的某个地方指定一个图像,它可能只会在打印时被调用onbeforeprint