JS解决PDF使用iframe打印报跨域错误问题的方法示例

作者:异步漫步时间:2026-10-31 12:44:56浏览:516

本文介绍如何在JavaScript中解决iframe打印PDF时触发的跨域安全限制。核心思路是将远程PDF文件转换为Blob二进制数据,利用createObjectURL生成同源本地对象URL,再注入隐藏的iframe调用print()接口,从而绕过浏览器同源策略导致的打印失败问题。

报错信息如下所示:

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 文件的二进制数据并转换为 Blob 对象,随后通过 window.createObjectURL 方法生成一个指向该 Blob 的本地资源 URL。最后,创建一个新的 iframe 元素,将其 src 属性设置为该本地 URL,并调用其 contentWindow.print() 接口执行打印操作。

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(); // 获取二进制数据
  })
  .then(blobData => {
      // 替换这里的 PDF_URL 为你要打印的 PDF 文件链接
      const PDF_URL = URL.createObjectURL(blobData);
    
      // 创建一个隐藏的 iframe 元素
      const iframe = document.createElement('iframe');
      // 等待 PDF 加载完成后进行打印
      iframe.onload = function() {
        iframe.contentWindow.print();
      };
      iframe.style.display = 'none';
      iframe.src = PDF_URL;
    
      // 将 iframe 添加到页面中
      document.body.appendChild(iframe);
  })
}

补充说明:处理 iframe 打印 PDF 时的跨域限制,关键在于利用 Blob 流将其转化为同源资源。

 <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)
    })

总结

至此,关于在 JavaScript 中通过 iframe 打印 PDF 时解决跨域报错的方法介绍完毕。如需了解更多相关技术细节,可查阅本站往期文章或继续浏览后续内容,感谢支持。

作者最新文章