仅在用户打印时如何重定向到另一页 [英] How to redirect to another page ONLY if the user prints

查看:64
本文介绍了仅在用户打印时如何重定向到另一页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试找到一种方法来重定向到另一页(如果用户实际打印).也就是说,我只希望他们在打印时打开的选项卡中单击该打印按钮时进行重定向.

I have been trying to find a way to redirect to another page if the user physically prints. That is, I want to redirect only if they click on that print button from the tab that opens when printing.

我不想要这种方法.

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

推荐答案

摘录自结合方法 如果将这两种方法结合使用,则可以在IE 5 +,Firefox 6 +,Chrome 9+和Safari 5.1+中检测打印请求(不幸的是Opera不支持这两种方法).

Combining the Approaches If you combine the two approaches you can detect print requests in IE 5+, Firefox 6+, Chrome 9+, and Safari 5.1+ (unfortunately Opera doesn’t support either approach).

(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中,每次打印请求都会调用它们两次.

Note that your event handlers might potentially have to deal with the fact that they’re going to be called twice per print request in Chrome.

摘录结束.

这篇关于仅在用户打印时如何重定向到另一页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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