【问题标题】:How to redirect to another page ONLY if the user prints仅当用户打印时如何重定向到另一个页面
【发布时间】:2018-07-24 23:33:39
【问题描述】:

如果用户进行物理打印,我一直在尝试找到一种重定向到另一个页面的方法。也就是说,只有当他们从打印时打开的选项卡中单击该打印按钮时,我才想重定向。

我不想要这种方法。

function myFunction() {
    window.print();
    window.location='http://newurl.com/';
}

【问题讨论】:

  • 您完全无法控制«打印时打开的标签»
  • 确实如此,但之前和之后都会发生一些事件。

标签: javascript php jquery html


【解决方案1】:

摘自以下https://www.tjvantoll.com/2012/06/15/detecting-print-requests-with-javascript/:

结合方法 如果结合这两种方法,您可以在 IE 5+、Firefox 6+、Chrome 9+ 和 Safari 5.1+ 中检测打印请求(不幸的是 Opera 不支持这两种方法)。

(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;
}());

请注意,您的事件处理程序可能必须处理这样一个事实,即在 Chrome 中每个打印请求都会调用它们两次。

摘录结束。

【讨论】:

  • 这些处理程序将在预览窗口关闭时(以及其他时间)运行,无论文档是否实际打印。
  • 基于 Chrome 的 (mediaquery) 将仅在实际打印时运行,除非 Chrome 切换到打印媒体进行预览...未测试。
  • 在 Chrome 68.0.3440.75 中,window.matchMedia('print') 的 beforePrint 和 afterPrint 在预览窗口出现之前都会触发,如果选择了不同的打印机,则会再次触发。 window.onafterprint 处理程序会在预览窗口关闭后触发,即使单击了取消也是如此。
  • 所以询问用户他或她之后是否真的打印了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-15
  • 1970-01-01
  • 1970-01-01
  • 2022-01-20
  • 2012-04-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多