Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS 8 Safari print redirect doesn't stop javascript execution

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);
like image 680
Corey W Avatar asked Oct 13 '14 18:10

Corey W


1 Answers

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
        });
    });
}
like image 175
Ben Vassmer Avatar answered Nov 03 '22 14:11

Ben Vassmer