记录-与iframe通信
背景
使用iframe内嵌页的时候,需求是需要给iframe传id
发布者和订阅者(监听者)的api
和web worker的类似,postMessage,onmessage
实际操作
首先弄清楚,双向的关系
上代码,方便理解:
// 文件的目录结构:├── index.html└── one-iframe.html
这是主线程:index.html
<!DOCTYPE html><html><head><meta charset="utf-8"><title>主线程</title><script type="text/JavaScript">// 并取得返回的数据function sendPost() {// 获取id为otherPage的iframe窗口对象var iframeWin = document.getElementById("otherPage").contentWindow;// 向该窗口发送消息iframeWin.postMessage('你要的参数,我给你');}// 监听跨域请求的返回window.addEventListener("message", function(event) {console.log(event, event.data);}, false);</script></head><body><input type="button" value="发送" onclick="sendPost()"><iframe src="./one-iframe.html" id="otherPage"></iframe></body>
这是iframe:one-iframe.html
<!DOCTYPE html><html><head><meta charset="utf-8"><title>我是iframe</title><script type="text/JavaScript">// 监听父窗口发送过来的数据向服务器发送post请求window.addEventListener("message", function( event ) {console.log(event.data)window.parent.postMessage('疯狂处理中... ok已完成'); // 给主程序发消息}, false);</script></head><body>我是iframe的内容</body></html>
点击按钮后,打印效果如下

码字不易,点赞鼓励
