Executing function before page gets to window.print()

前端 未结 4 889
慢半拍i
慢半拍i 2020-12-16 03:19

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

4条回答
  •  天涯浪人
    2020-12-16 03:40

    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.

提交回复
热议问题