9

我在我的项目中使用打印(使用 HTML 和 javascript)。在 mozilla 中,onbeforeprint 和 onafterprint 可以正常工作,但不能在 chrome 中工作。

4

6 回答 6

11

适用于 Chrome 的是在“窗口”中检查“matchmedia”,如下所示:

                if ('matchMedia' in window) {
                    window.matchMedia('print').addListener(function (media) {
                    //do before-printing stuff
                    });
                } else {
                    window.onbeforeprint = function () {
                    //do before-printing stuff
                    }
                }
于 2015-04-28T20:21:24.850 回答
3

根据他们的变更日志,这适用于 Chrome 63。

于 2018-09-19T13:04:53.267 回答
2

快速更新,因为对打印事件的支持改进了很多

  • Chrome 63,2017 年 12 月发布,支持它
  • Opera 50 也是如此
  • Edge 从一开始就支持它
  • 甚至 IE 的旧版本 6 (6!!) 也支持它
于 2018-02-11T10:08:10.643 回答
1

Chrome 没有 onbeforeprint。

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

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

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

于 2013-01-24T16:19:56.987 回答
1

Chrome 不支持这些事件。相反,它支持' window.matchMedia '。Chrome中还有一个错误,阻止它打印所有页面。出于这个原因,我建议您在网页中添加一个打印按钮,并要求用户使用该按钮,而不是通过 Chrome 菜单进行打印。

var beforePrint = function() {
    console.log("before");
};
var afterPrint = function() {
    console.log("after");
};

var launchedFromMenu = true;
if (window.matchMedia) {
    var mediaQueryList = window.matchMedia('print');
    mediaQueryList.addListener(function(mql) {
        if (mql.matches) {
            if(launchedFromMenu) {
                // https://bugs.chromium.org/p/chromium/issues/detail?id=571070
                alert("There is a bug in Chrome/Opera and printing via the main menu does not work properly. Please use the 'print' icon on the page.");
            }
            beforePrint();
        } else {
            afterPrint();
        }
    });
}

// These are for Firefox
window.onbeforeprint = beforePrint;
window.onafterprint = afterPrint;

function printPage() {
    window["beforePrint"]();
    launchedFromMenu = false;
    window.print();

}
于 2017-02-03T22:22:28.917 回答
-1

在 Chrome 中,onbeforeprint 和 onAfterPrint 不起作用。

但是您可以通过使用 css 打印媒体来限制打印页面

例子

<link rel="stylesheet" href="print.css" type="text/css" media="print" />

此 css 包含在页面的标题中。

具有以下样式的 css

#header, #menu, #entry-content, .noprint {display: none;}
于 2013-09-27T06:33:32.997 回答