亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

js解決pdf使用iframe打印報跨域錯誤問題的方法示例

 更新時間:2024年03月27日 09:47:29   作者:舜岳  
這篇文章主要給大家介紹了關(guān)于js解決pdf使用iframe打印報跨域錯誤問題的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用js具有一定的參考借鑒價值,需要的朋友可以參考下

報錯如下:

Uncaught DOMException: Failed to read a named property ‘print’ from ‘Window’: Blocked a frame with origin “https://xxxx.com” from accessing a cross-origin frame.
at iframe.onload (:10:26)

解決方法:

把 pdf 轉(zhuǎn) blob 二進(jìn)制數(shù)據(jù), 通過 createObjectURL 生成本地對象 url, 在創(chuàng)建 iframe 調(diào)用打印接口

printPDF()
function printPDF() {
  fetch('https://xxxxx.com/xxxx.pdf')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    } 
    return response.blob(); // 獲取二進(jìn)制數(shù)據(jù)
  })
  .then(blobData => {
      // 替換這里的 PDF_URL 為你要打印的 PDF 文件鏈接
      const PDF_URL = URL.createObjectURL(blobData);
    
      // 創(chuàng)建一個隱藏的 iframe 元素
      const iframe = document.createElement('iframe');
      // 等待 PDF 加載完成后進(jìn)行打印
      iframe.onload = function() {
        iframe.contentWindow.print();
      };
      iframe.style.display = 'none';
      iframe.src = PDF_URL;
    
      // 將 iframe 添加到頁面中
      document.body.appendChild(iframe);
  })
}

附:iframe打印pdf跨域問題,使用blob流轉(zhuǎn)為同源

 <iframe :src="pdfUrl2" width="100%" height="700px" id="printMe" hidden></iframe>
 <iframe :src="pdfUrl" width="100%" height="700px"></iframe>
 
import axios from 'axios'
 axios({
    method: 'get',
    url: this.pdfUrl,
    responseType: 'blob'
  })
   .then(response => {
    this.pdfUrl2= window.URL.createObjectURL(response.data)
    setTimeout(() => { 
      document.getElementById('printMe').contentWindow.print();
     },2000) 
 
    })
      .catch(function(error) {
       console.log(error)
    })

總結(jié) 

到此這篇關(guān)于js解決pdf使用iframe打印報跨域錯誤問題的文章就介紹到這了,更多相關(guān)js pdf用iframe打印報跨域錯誤內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論