关于iframe 打印事件的回调 并没有触发

534 阅读1分钟

<script setup lang="ts">
import { ref, watch, onMounted } from "vue"
import pdfFile from "../assets/326_ParcelLabelingGuide-1 - 副本【搜狗文档翻译_双语_英译中】.pdf"
const iframeRef = ref()



watch(iframeRef, (newValue, oldValue) => {
  console.log(newValue, oldValue, 'watchers')
  console.log(newValue.value)
  if (newValue) {
    console.log(newValue.contentWindow, 'ele')
    newValue.onload = () => {
      console.log("load")
      newValue.contentWindow.addEventListener('afterprint', () => {
        console.log('after print')
      })
    }
    const afterprintfn = () => {
      let mediaQueryList = newValue.contentWindow.matchMedia('print')
      mediaQueryList.addListener((mql) => {
        if (mql.matches) {
          console.log('onbeforeprint equivalent');
        } else {
          console.log('onafterprint equivalent');
        }
      });
    }
    newValue.contentWindow.onafterprint = afterprintfn

  }
}, { deep: true })

const pdfUrl = ref(pdfFile)
const handlePdfClick = () => {
  console.log("iframeRef", iframeRef.value, iframeRef.value.contentWindow)
  iframeRef.value.contentWindow.print()

}
const onload = () => {
  console.log("load")
}

</script>

<template>
  <div class="test-iframe">
    <iframe class="iframe-box" title="PDF文件" id="Iframe" :src="pdfUrl" ref="iframeRef" @onload="onload" />
    <button @click="handlePdfClick">打印</button>
  </div>
</template>

<style scoped>
.iframe-box {
  width: 1200px;
  height: 800px;
}
</style>

onafterprint 事件并没有触发 有没有大佬指点一下 用react也试了试