Connor Bishop Connor Bishop - 4 months ago 32
Javascript Question

Confirmation message after window.print()

Its well known that there is no way to determine whether a user clicked print or cancel on the print window produced by window.print().

So Im stuck with the next best thing which is to basically ask the user if they did print successfully.

I have this:

$(document).ready(function(){

window.print();

var a = confirm('Confirm printing as successfull and mark Job Cards as Released?');
if(a == true) {
$.post('PrintSuccess');
window.location = '/Menu';
}
});


Trouble is, the confirmation box pops up before the print window does, how can ensure the print window appears first?

Answer

There are a few ways to make sure a print dialog is finished before running a code block. Browser support varies, so you may need to combine some of them to match your need. See below stackoverflow topics.

The following code should work for most modern browsers.

var printCompleteCallback = function () {
    var conf = confirm('Confirm printing as successfull and mark Job Cards as Released?');
    if (conf) {
        if (a == true) {
            $.post('PrintSuccess');
            window.location = '/Menu';
        }
    }
}

window.print();
if (window.onafterprint) { //check if browser supports window.onafterprint event handler (Firefox and IE)
    $(window).one("afterprint", printCompleteCallback);
}
else { //Use setTimeout solution if onafterprint is not supported (Chrome)
    setTimeout(printCompleteCallback, 0);
}