仅在用户打印时如何重定向到另一页

时间:2018-07-24 23:33:39

标签: javascript php jquery html

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

我不想要这种方法。

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

1 个答案:

答案 0 :(得分: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中,每次打印请求都会调用它们两次。

摘录结束。