Executing function before page gets to window.print()

前端 未结 4 885
慢半拍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.

    0 讨论(0)
  • 2020-12-16 03:53

    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>
    
    0 讨论(0)
  • 2020-12-16 03:58

    "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.

    0 讨论(0)
  • 2020-12-16 04:02

    You should be able to override it like so...

    var _print = window.print;
    window.print = function() {
      alert("Hi!");
      // do stuff
      _print();
    }
    
    0 讨论(0)
提交回复
热议问题