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