iFrame跨源通信 [英] iFrame Cross Origin Communication

查看:505
本文介绍了iFrame跨源通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 iFrame src加载的其中一个js文件中访问父对象。页面和 iFrame src位于不同的域中。由于网络安全和相同的原始政策,我得到未捕获的安全错误: 阻止带有来源的框架http://example.com:1211访问交叉原始框架

I am trying to access parent object from one of the js files that was loaded by iFrame src. The page and iFrame src are in different domains. Due to web security and same origin policy, I am getting "Uncaught SecurityError: Blocked a frame with origin "http://example.com:1211" from accessing a cross-origin frame".

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

Need to access a parent object and set to one of the iFrame variable. So, I lost the option of window.postMessage(). Is there any way to solve this issue ? Please suggest some ways.

推荐答案

像SilverlightFox所说,postMessage()应该适用于不同的域。

Like SilverlightFox says, postMessage() should work across different domains.

您是否可以访问父级和iframe src?如果是这样,你可以在iframe src中输入这样的内容来发送消息:

Do you have access to both the parent and iframe src? If so, you can put something like this in your iframe src to send the message:

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

然后在您的父母中收到消息:

And then in your parent, receive the message:

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

这篇关于iFrame跨源通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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