如何使用CORS访问iframe

Pau*_*per 17 javascript iframe cors

当用户打印时,我的服务器生成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');
Run Code Online (Sandbox Code Playgroud)

但现在我在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.
Run Code Online (Sandbox Code Playgroud)

我认为我需要添加CORS头.

我有

Access-Control-Allow-Methods: GET, HEAD
Access-Control-Allow-Origin: *
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

Ray*_*lus 28

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

  • 我想知道为什么CORS不适用于跨源iframe.如果iframe的内容明确允许来自其他来源的访问,为什么iframe会从此排除? (12认同)
  • 您可能想要添加CORS的用途. (5认同)
  • 用户与 iframe 内容的交互不是问题。通过设置 CORS 标头,iframe 中的页面提供了对包括 iframe 在内的页面的完全访问权限。我想,这可能会导致安全问题,因为访问页面可能会被破坏,从而操纵 iframe 页面的内容。这就是为什么存在 `w​​indow.postMessage()` 的原因,它提供了两者之间的受限交互。但也许这就是你的意思。:-) (3认同)
  • @Ray,你能用代码解释一下吗?我在这里有点迷失了。谢谢! (2认同)