检测用户是否通过 javascript 打印内容 [英] Detect if a user prints something via javascript

查看:40
本文介绍了检测用户是否通过 javascript 打印内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've got a problem with detecting a print event in javascript. For example, a user wats to print document and presses print in a web-page, then another window appers, e.g. to print from Adobe Reader, then appears another window of Adobe Reader where you can set properties, choose pages to print and what not...and there is the print button in this window. Can I actually detect when the user presses this print button inside this Adobe Reader window in browser using javascript?

我已经尝试过使用 onafterprint 但也许我没有正确使用或者我不知道.

I've already tried using onafterprint but maybe I didn't do this correctly or I'dont know.

它在我的主 js 文件中是这样的.

it was something like this inside my main js file.

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/

推荐答案

您是否意识到您的代码什么都不做?这个会帮助你.

Do you realize that you code do nothing ? This one will help you.

(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,您应该会看到消息.

run it in your dev console on any open page, then hit ctrl-P and you should see message.

这篇关于检测用户是否通过 javascript 打印内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆