Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use CORS to access an iframe

Tags:

When a user prints, my server generate a PDF, and I do this to show the print dialog for the PDF.

$('<iframe type="application/pdf"></iframe>').attr('src', url).load(function() {     var iframe = this;     setTimeout(function() { //Chrome PDF viewer shows "Loading..." forever otherwise         iframe.contentWindow.print();         $(iframe).remove(); //gc     }, 50); }).appendTo('body'); 

But now I am hosting the PDFs on S3. I get

Uncaught SecurityError: Blocked a frame with origin "https://localhost" from accessing a frame with origin "https://my-bucket.s3.amazonaws.com". Protocols, domains, and ports must match. 

I presume I need to add CORS headers.

I have

Access-Control-Allow-Methods: GET, HEAD Access-Control-Allow-Origin: * 

What am I missing?

like image 401
Paul Draper Avatar asked Mar 14 '14 18:03

Paul Draper


People also ask

How do I access cross domain iframe?

To access cross-domain iframe, the best approach is to use Javascript's postMessage() method. This method provides a way to securely pass messages across domains.

How do you resolve cross origin issues in iframe?

You need control over the domain you want to embed to remove/amend its CORS policy. If the domain has explicitly blocked Cross-Origin requests, there's nothing you can do about it.

Can an iframe access its parent DOM?

If the content of the iframe and its parent have the same domain, you can access the parent pages DOM from the iframe by using parent. document.


1 Answers

Paul - CORS does not apply when attempting to programmatically access content from a cross-origin iframe. If you want to access content from an iframe on a different domain, you will need to make use of the Web Messaging API (window.postMessage & the onmessage event) to communicate between your page and the iframe.

like image 190
Ray Nicholus Avatar answered Sep 20 '22 17:09

Ray Nicholus