I have a page that calls window.print(); at the bottom of the page. I have no way of accessing the code around window.print(); Its generated by the server and I can\'t tou
This function works for all browsers including IE, no matter how the print is called:
/**
* Adds listeners for crossbrowser print callback
* @param callback - callback function
*/
function onPrint(callback) {
window.matchMedia('print').addListener(query => query.matches ? callback() : null)
window.addEventListener('beforeprint', () => callback())
}
onPrint(() => console.log('printing!'))
Be aware it may run the callback function twice, depending on the browser. This could be circumvented with a temporary flag.
Try putting another <script>
tag before the one you don't have access to eg:
<html><head></head><body></body><script>alert('Hello There !');</script><script>window.print();</script></html>
"Basically because of IE I need to..."
If you only need support for IE, see the onbeforeprint event.
window.onbeforeprint = function () {
// some code
}
The benefit here is that the code will not run in browsers that don't support onbeforeprint, which is pretty much every browser except IE.
You should be able to override it like so...
var _print = window.print;
window.print = function() {
alert("Hi!");
// do stuff
_print();
}