如何使用 CORS 访问 iframe [英] How to use CORS to access an iframe
问题描述
当用户打印时,我的服务器生成一个 PDF,我这样做是为了显示 PDF 的打印对话框.
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');
但现在我在 S3 上托管 PDF.我明白了
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.
我想我需要添加 CORS 标头.
I presume I need to add CORS headers.
我有
Access-Control-Allow-Methods: GET, HEAD
Access-Control-Allow-Origin: *
我错过了什么?
推荐答案
Paul - 尝试以编程方式从跨域 iframe 访问内容时,CORS 不适用.如果您想从不同域上的 iframe 访问内容,您将需要使用 Web Messaging API(window.postMessage
和 onmessage
事件)来在您的页面和 iframe 之间进行通信.
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.
这篇关于如何使用 CORS 访问 iframe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!