如何使用CORS访问iframe [英] How to use CORS to access an iframe

查看:745
本文介绍了如何使用CORS访问iframe的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户打印时,我的服务器生成PDF,并显示PDF的打印对话框。

  $('< iframe type =application / pdf>< / iframe>')。attr('src',url).load(function(){
var iframe = this;
setTimeout(function(){// Chrome PDF查看器永远显示正在加载...否则
iframe.contentWindow.print();
$(iframe).remove(); // gc
},50);
})appendTo('body');

但现在我在S3上托管PDF。我获得

 未捕获SecurityError:从
阻止了带有来源https:// localhost的框架来源https://my-bucket.s3.amazonaws.com。
协议,域和端口必须匹配。

我假设我需要添加 CORS 标题。



我有

 访问控制允许方法:GET,HEAD 
访问控制允许原产地:*
/ pre>

我失踪了什么?

解决方案

Paul - CORS在尝试以编程方式访问来自跨源iframe的内容时不适用。如果您要从其他网域上的iframe访问内容,则需要使用Web Messaging API( window.postMessage & the onmessage event)在页面和iframe之间进行通信。


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?

解决方案

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆