【问题标题】:iFrame Cross Origin CommunicationiFrame 跨域通信
【发布时间】:2014-09-14 18:27:14
【问题描述】:

我正在尝试从 iFrame src 加载的 js 文件之一访问父对象。页面和 iFrame src 位于不同的域中。由于网络安全和同源策略,我收到“Uncaught SecurityError: Blocked a frame with origin "http://example.com:1211" from accessing a cross-origin frame".

需要访问父对象并设置为 iFrame 变量之一。所以,我失去了 window.postMessage() 的选项。有没有办法解决这个问题?请提出一些方法。

【问题讨论】:

  • I lost the option of window.postMessage() 是什么意思?应该可以吗?
  • 我在父级中使用 session.js 并希望访问 iframe 源中的对象。如果我试图将对象转换为字符串,以便我可以通过 postmessage 发送。但是得到了,未捕获的类型错误:将循环结构转换为 JSON。我是这个领域的新手,你能建议我什么吗? Bcz i hv 在我的项目中的许多地方与父母沟通。

标签: html security iframe same-origin-policy


【解决方案1】:

就像 SilverlightFox 所说,postMessage() 应该可以跨不同的域工作。

您是否可以同时访问父源和 iframe src?如果是这样,您可以在您的 iframe src 中放置类似的内容来发送消息:

<script type="text/javascript">
function post(msg) {
        var msg = "Do something"; // Can be string or numeric.
        parent.postMessage(msg, '*');
    }
    post();
</script>

然后在你的父母中,接收消息:

<script>    
function listener(event){ 
   if (event.origin !== 'https://myotherdomain.com' ){  //Optional check for message source
      return 
   }
   var info = event.data;
   DoSomething(info);
}

// Set up event handler when parent page loads.

if (window.addEventListener){ 
   addEventListener("message", listener, false) 
} else { 
   attachEvent("onmessage", listener) 
}
</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-13
    • 2023-03-12
    相关资源
    最近更新 更多