Created
March 11, 2019 16:26
-
-
Save capturetheflag/a588f4d5919efebf2eae315aeb9e2297 to your computer and use it in GitHub Desktop.
window.print() and Safari's print confirmation dialog
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@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.