iframe的跨域问题
- 有两个页面,父页面域名
http://localhost:9001
,子页面域名http://127.0.0.1:9081
,如下图:
- 父页面和子页面域名不同,如果两个页面相互调用对方的方法和属性,会提示跨域:
Uncaught DOMException: Blocked a frame with origin “http://localhost:9001” from accessing a cross-origin frame. at http://localhost:9001:46
使用window.postMessage()
实现跨域通信
window.postMessage()
文档,文档中还说明了浏览器的兼容性,可以根据项目的实际情况决定是否采用。- 父页面增加代码如下:
<script type="text/javascript">
//响应事件,监听接收子页面的消息
window.addEventListener('message', function (event) {
console.log("来自127.0.0.1的消息:" + event.data);
}, false);
//向子页面http://127.0.0.1:9081发消息,setTimeout是保证调起子页面后再发送消息,可以做成按钮等事件触发
setTimeout(function () {
window.frames["layui-layer-iframe1"].postMessage("我是localhost", "http://127.0.0.1:9081");
}, 5000);
</script>
- 子页面增加代码如下:
<script type="text/javascript">
//响应事件,监听接收父页面的消息
window.addEventListener('message', function (event) {
console.log("来自localhost的消息:" + event.data);
}, false);
//向父页面http://localhost:9001发送消息
window.parent.postMessage("我是127.0.0.1", "http://localhost:9001");
</script>
- 打开页面,控制台打印消息如下:
- 可以看到父页面和子页面都收到了对方发送的消息。