-1

I have and Iframe in a react component which loads a pdf file on click of button from an external url (My Api endpoint with port 8000), After It's loaded successfully, I want to print the content of that Iframe, But getting and error

Here is my react component

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

I am making Request from front end which has a url of 127.0.0.1:4100 . I feel this error is due to the fact that the Iframe source and request origin has different protocols.

doupix_9ja
  • 11
  • 5
  • Please [**search**](/search?q=Blocked+a+frame+with+origin+from+accessing+a+cross-origin+frame) before posting and if you post anyway, say why those previous answers didn't solve your problem. More about searching [here](/help/searching). – T.J. Crowder Feb 10 '21 at 15:04

1 Answers1

0

You can't access cross-origin iframes directly.

There are methods to communicate, through iframes, between HTML documents on different origins but they don't apply here since you are loading a PDF.

A few approaches you could take for dealing with this are:

  • Use the same origin for both documents
  • Convert the PDF to HTML
  • Fetch the HTML with Ajax (you'll need CORS) and then render it with something like Mozilla's PDF.js
Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205