【问题标题】:Uncaught (in promise) DOMException: Blocked a frame with origin "http://127.0.0.1:4100" from accessing a cross-origin frame - REACT JS [duplicate]未捕获(承诺中)DOMException:阻止具有源“http://127.0.0.1:4100”的框架访问跨域框架-REACT JS [重复]
【发布时间】:2021-02-10 23:04:30
【问题描述】:

我在一个反应​​组件中有 Iframe,该组件在单击外部 url 按钮时加载一个 pdf 文件(我的 Api 端点,端口为 8000),成功加载后,我想打印该 Iframe 的内容,但是获取和错误

这是我的反应组件

import React from 'react'

const pageCont = () =>{
   return(
     <div>
         <iframe id='pdfp' name='pdfp' src='http://127.0.0.1:8000/api/ebook.pdf'></iframe>
         <button onClick={()=>{
            document.getElementById("pdfp").contentWindow.focus()
            document.getElementById("pdfp").contentWindow.print()}
          }>
Print Iframe
        </button>
    </div>
    )
}
export default pageCont;

Uncaught (in promise) DOMException: Blocked a frame with origin "http://127.0.0.1:4100" from accessing a cross-origin frame

我正在从前端发出请求,其 URL 为 127.0.0.1:4100 。我觉得这个错误是由于 iframe 源和请求源具有不同的协议。

【问题讨论】:

  • 请在发帖前search,如果您仍然发帖,请说明为什么以前的答案没有解决您的问题。更多关于搜索here.

标签: javascript reactjs


【解决方案1】:

您不能直接访问跨域 iframe。

There are methods to communicate, through iframes, between HTML documents on different origins 但它们不适用于此处,因为您正在加载 PDF。

您可以采取以下几种方法来处理此问题:

  • 对两个文档使用相同的来源
  • 将 PDF 转换为 HTML
  • 使用 Ajax 获取 HTML(您需要 CORS),然后使用类似 Mozilla 的 PDF.js 之类的内容进行渲染

【讨论】:

    猜你喜欢
    • 2018-12-14
    • 2019-01-19
    • 2018-10-14
    • 2018-11-28
    • 2017-10-02
    • 2014-09-25
    相关资源
    最近更新 更多