9

I have the need to provide the ability to print a label on successful save and after the print redirect to a search page. This works in chrome, firefox, ie, iOS 6/7 safari, etc. However, it seems that iOS 8 no longer stops the execution of javascript when window.print() is issued from javascript.

If you navigate to this jsfiddle example from iOS 8 Safari (connected to a computer so you can view the console logs) and click the Print button you will see that the console.log will trigger when the print dialog is up. So if you want to print and then navigate you will print the wrong screen unless you have a delay that gives you enough time to hit print which isn't acceptable in this case.

I did an artificial delay because in iOS 6/7 that seemed to get the print dialog to eventually stop the execution of javascript. In that case 500ms was enough to make it work.

Has anyone else seen this issue when doing a similar thing in iOS 8 from Safari? Have they introduced a new event to listen for that I could use to do this?

// Example Code
window.print();
setTimeout(function() {
    console.log('This should print after the print is issued in the iOS print dialog.');
}, 500);
Corey W
  • 93
  • 4
  • The following may be similar for a previous version of chrome but it doesn't seem to be fully true because the setTimeout would fix it... [Print Window Close Results in Print Preview](http://stackoverflow.com/questions/7652981/chrome-window-print-window-close-results-in-print-preview-failed-solution) – Corey W Oct 14 '14 at 18:51
  • I am still curious if anyone has found a solution to this so feel free to reply and let me know. Right now I am going to have to look at the user agent for iOS 8 and put in a different flow for the print and redirect that will make it a manual touch to continue type of thing. Thanks in advance! – Corey W Oct 15 '14 at 18:05

1 Answers1

8

You can use window.matchMedia (caniuse link), combined with window.onbeforeprint and window.onafterprint (for earlier IE support). A good reference for using matchMedia can be found here and here.

To satisfy using matchMedia with iOS, use nested events. First, listen for the media type to change to print. Then, inside that callback, listen for the media to change back to screen.

if (window.matchMedia) {
    var printQuery = window.matchMedia('print');
    printQuery.addListener(function() {
        var screenQuery = window.matchMedia('screen');
        screenQuery.addListener(function() {
            //actions after print dialog close here
        });
    });
}
Community
  • 1
  • 1
Ben Vassmer
  • 194
  • 8