Skip to content

Instantly share code, notes, and snippets.

@capturetheflag
Created March 11, 2019 16:26
Show Gist options
  • Save capturetheflag/a588f4d5919efebf2eae315aeb9e2297 to your computer and use it in GitHub Desktop.
Save capturetheflag/a588f4d5919efebf2eae315aeb9e2297 to your computer and use it in GitHub Desktop.
window.print() and Safari's print confirmation dialog
// If a user cancels print and then tries to print again, Safari will display its print confirmation dialog.
// We want to perform some actions as soon as printing finishes, neither earlier nor later.
// The problem is: Safari's print confirmatiog dialog does not stop JS code execution flow
// therefore all lines below window.print() are executed before actual printing starts
// More details here: https://stackoverflow.com/q/50455545/1177964
// Tested to work in: Safari 12, macOS 10.14 (Mojave)
function safariPrint() {
// Safari
if (!window.onafterprint) {
const onAfterPrint = mql => {
window.onfocus = null;
if (!mql.matches) {
console.log('after print');
document.getElementById('print-section').className = 'hidden';
if (mediaQueryList.removeEventListener) {
mediaQueryList.removeEventListener('change', onAfterPrint);
} else {
mediaQueryList.removeListener(onAfterPrint);
}
}
};
// emulate onbeforeprint/onafterprint
const mediaQueryList = window.matchMedia('print');
if (mediaQueryList.addEventListener) {
mediaQueryList.addEventListener('change', onAfterPrint);
} else {
mediaQueryList.addListener(onAfterPrint);
}
// if a user cancels printing in Safari's print confirmation dialog
// then we will trigger a cleanup
window.focus();
window.onfocus = () => {
onAfterPrint(mediaQueryList);
};
console.log('before print');
document.getElementById('print-section').className = '';
}
window.print();
}
@kkreft
Copy link

kkreft commented Nov 5, 2021

@capturetheflag Thanks for this gists, I'm trying to make a workaround for a printing issue for Safari for a while. I've checked your solution on different Safari versions and indeed, it works for Safari 12.1 but unfortunately not on 15.1.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment