如何使用CORS访问iframe

问题描述 投票:0回答:2

当用户打印时,我的服务器会生成 PDF,我这样做是为了显示 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。我明白了

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 标头。

我有

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

我错过了什么?

javascript iframe cors
2个回答
34
投票

当尝试以编程方式从跨源 iframe 访问内容时,CORS 不适用。如果您想从不同域上的 iframe 访问内容,则需要使用 Web Messaging API(

window.postMessage
onmessage
事件)在页面和 iframe 之间进行通信。


0
投票

有了对顶部窗口的引用,您可以以编程方式创建脚本并将其 insideHTML 设置为您想要执行的内容。之后,您可以将其附加到顶部窗口的文档头,浏览器将执行它。

© www.soinside.com 2019 - 2024. All rights reserved.