1

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?

Connor Bishop
  • 921
  • 1
  • 12
  • 21

2 Answers2

1

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);
}
Community
  • 1
  • 1
Ozan
  • 3,709
  • 2
  • 18
  • 23
  • code works in chrome, thanks. how does the if(window.onafterprint) bit work ? – Connor Bishop Aug 08 '16 at 11:19
  • It's supposed to check if the browser supports the `onafterprint` event, but it's not quite right. It should be `if( 'onafterprint' in window)` – Niet the Dark Absol Aug 08 '16 at 11:20
  • 1
    @ConnorBishop, `window.onafterprint` is an event handler that is fired after a print dialog is finished, but [browser support](https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onafterprint#Browser_compatibility) for it is very limited. So we check if the browser supports it and use it if it does. We fallback to `setTimeout` solution (which works in chrome) if the browser does not support afterprint event. I added comments to the code explaining it. – Ozan Aug 08 '16 at 11:23
0
window.onafterprint = function() {
    var a = confirm('Confirm printing as successfull and mark Job Cards as Released?');
    if(a == true) {
        $.post('PrintSuccess');
        window.location = '/Menu';
    }
}
chris97ong
  • 6,870
  • 7
  • 32
  • 52