【问题标题】:Receiving data from cross-origin iframe从跨域 iframe 接收数据
【发布时间】:2019-11-15 21:12:29
【问题描述】:

我需要从跨域 iframe 接收数据。 Iframe 内容网站也是我的。每个人都说 postMessage() 在两个方向上都有效,但不适合我。
如果有人对我的问题有一些经验,我将非常感激:)

在 iframe 的网站代码中

window.postMessage("ehooo!", "*");

在网站代码中

<iframe src="https://ehooo.com" name="iframe" onLoad="iframeLoaded()"></iframe>
<script>
  function iframeLoaded() {
    event.target.contentWindow.addEventListener("message", e => {
      console.log(e.data);
    });
  }
</script>

控制台输出

Uncaught DOMException: Blocked a frame with origin "https://ehooo.com" from accessing a cross-origin frame.

【问题讨论】:

    标签: javascript html iframe


    【解决方案1】:

    好的,伙计们,我想通了。所以在我要求 iframe 给我消息而不是窗口之前。我这样做是因为窗户什么也没给我。看起来如果您从 iframe 发送到父级,我们需要将 postMessage 设置为父级并要求将消息发送到窗口对象。我是从 (here) 那里得到的,有点复杂,设计过度,但给了我正确的线索。

    在 iframe 代码中

    window.parent.postMessage("ehooo!", "*");
    

    在网站代码中

    <iframe src="https://ehooo.com" name="iframe"></iframe>
    <script>
        window.addEventListener("message", e => console.log(e.data));
    </script>
    

    【讨论】:

    • 感谢这个简单的例子。完全同意你关于它被过度设计的看法。读到 W3 推荐书让我头疼。
    【解决方案2】:

    您应该使用 .htaccess 文件从 iframe 网站向 iframe 接收者网站授予权限

    # Sets CORS headers for request from example1.com and example2.com pages
    # for both SSL and non-SSL
    SetEnvIf Origin "^https?://[^/]*(reciverewebsite)\.com$" ORIGIN=$0
    Header set Access-Control-Allow-Origin %{ORIGIN}e env=ORIGIN
    Header set Access-Control-Allow-Credentials "true" env=ORIGIN
    # Always set Vary: Origin when it's possible you may send CORS headers
    Header merge Vary Origin
    

    它适用于我的项目

    【讨论】:

    • 我忘了说,我使用的是 Node Express。我为双方设置了 req.header("Access-Control-Allow-Origin", "*") 但仍然没有:(
    • 噢,不幸的是,我没有针对这种情况的任何其他解决方案。对不起。
    • 没关系,还是谢谢你:)
    猜你喜欢
    • 1970-01-01
    • 2023-03-15
    • 2012-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-17
    • 1970-01-01
    相关资源
    最近更新 更多