joseluisq / printd

Print HTML elements or pages in modern browsers.
MIT License
80 stars 5 forks source link

Printd event `afterprint` not work on Chrome #21

Closed roeurbnavy closed 1 year ago

roeurbnavy commented 1 year ago

Specifications

Steps will reproduce the problem.

(1) Press 'print button' (2) Cancel print modal

My code

  mounted() {
    // Printd
    this.d = new Printd()
  },
  methods: {
    print() {
      const callback = ({ launchPrint }) => {
        launchPrint()
      }

      this.d.print(document.getElementById('printing'), [], [], callback)

      // then add your event handlers
      const { contentWindow } = this.d.getIFrame()
      if (contentWindow) {
        contentWindow.addEventListener('beforeprint', () => {
          console.log('before print event!')
        })
        contentWindow.addEventListener('afterprint', () => {
          console.log('after print event!')
        })
      }
    },
  },

https://user-images.githubusercontent.com/20157836/212275985-cc70cb40-6094-404e-926e-1764d8cc8e10.mov

joseluisq commented 1 year ago

Just move your browser print events after calling d.print(). See https://codepen.io/joseluisq/pen/VzRpGb (updated). Tested on latest Chrome 110.0.5481.77

The reason is that, although the underlying iframe gets created once Printd is instantiated BUT the whole content to be printed is always replaced in the iframe (emptied) once either print or printURL methods are called.

Maybe Printd should make it easier and add support for beforeprint and afterprint in its API directly.

joseluisq commented 1 year ago

Added two methods to ease printing events. See v1.6.0

ApplY3D commented 1 year ago

Screenshot 2023-06-05 at 14 06 04 in Firefox both events fires before print. Tested on https://codepen.io/joseluisq/pen/VzRpGb