GWT处理浏览器窗口的打印事件

时间:2017-06-07 04:15:54

标签: javascript gwt

我需要在用户点击"打印"按钮或发出Ctrl + P.原因是我们在GWT应用程序中添加了一个打印方法,可以准备好打印输出。这不能用CSS完成。因此我们需要捕获事件。我已经在https://www.tjvantoll.com/2012/06/15/detecting-print-requests-with-javascript/找到了这个,但我不确定如何在GWT中实现它?任何帮助表示赞赏。

我使用GWT 2.8。

祝你好运 汉纳斯

1 个答案:

答案 0 :(得分:0)

毕竟我用这种方式解决了这个问题,我通过这种方式学到了很多关于JSNI的知识: - )

public native void handlePrintEvent() /*-{

    var theInstance = this;
    (function() {
        var beforePrint = function() {
            console.log('Functionality to run before printing.');
            theInstance.@com.myproject.xyz::preparePrint()();
        };
        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;
    }());
}-*/;

变量theInstance非常重要,否则无效!

应该在Widget(com.myproject.xyz)类的C'tor中调用此函数来安装打印处理程序

然后你需要实现函数preparePrint()来执行一些特定于打印的逻辑(这实际上是我需要的)。

希望别人找到这个有用的