javascript - 检测用户是否通过 JavaScript 打印内容

标签 javascript printing

我在检测 JavaScript 中的打印事件时遇到问题。 例如,用户想要打印文档并在网页中按下打印,然后出现另一个窗口,例如从 Adob​​e Reader 进行打印,然后会出现 Adob​​e Reader 的另一个窗口,您可以在其中设置属性、选择要打印的页面等等...并且此窗口中有打印按钮。我真的可以使用 javascript 检测用户何时在浏览器中的 Adob​​e Reader 窗口内按下此打印按钮吗?

我已经尝试过使用 onafterprint 但也许我没有正确执行此操作,或者我不知道。

我的主 js 文件中是这样的。

window.onbeforeprint = function() {
    console.log('This will be called before the user prints.');
};
window.onafterprint = function() {
    console.log('This will be called after the user prints');   
};

我从这里获取的:https://www.tjvantoll.com/2012/06/15/detecting-print-requests-with-javascript/

最佳答案

您是否意识到您的代码什么也没做? 这个会对你有所帮助。

(function() {
    var beforePrint = function() {
        console.log('Functionality to run before printing.');
    };
    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;
}());

在任何打开的页面上的开发控制台中运行它,然后按 ctrl-P,您应该会看到消息。

关于javascript - 检测用户是否通过 JavaScript 打印内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44918212/

相关文章:

javascript - 在 Meteor 的模板渲染函数中访问父数据上下文

javascript - 仅在通过脚本访问时未定义属性

javascript - 使用 JQuery 监听除特定 div 及其子元素之外的所有 html 正文点击

c - 在c中打印多八位字节字符

java - 打印 PDF 时出现奇怪的符号

javascript - 将日期时间字符串从 C# 转换为 Javascript 中的日期对象

javascript - AngularJS 实现 ui-grid

java - 使用 Java 打印机换行符无法正常工作

.net - 为什么 LocalPrintServer.GetDefaultPrintQueue() 在域中的机器上失败

css - 通过 @page css 设置打印边距内容不起作用