otherWindow.postMessage(message, targetOrigin, [transfer])方法实现 与iframe通信
*IE有兼容问题
index.html页面
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>.green {padding: 10px;border: 1px solid green;margin-bottom: 20px;}#frame {width: 100%;}</style></head><body><div class="green"><p> 父页面信息</p><button id='btn'>向子传参</button><div id='yy'></div></div><iframe src="./frame.html" id="frame" frameborder="0"></iframe><script>var yy = document.querySelector('#yy')// 父页面接收子页面的参数window.addEventListener('message', function (e) {console.log(e)yy.innerHTML = e.data.a})// 父页面传给子页面的参数var btn = document.querySelector('#btn')btn.addEventListener('click', function (e) {var contentWindow = document.querySelector('#frame').contentWindowcontentWindow.postMessage({ b: '父传给子的' }, '*')})</script></body></html>
frame.html页面
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>.red {padding: 10px;border: 1px solid red;}body{margin: 0;}</style></head><body><div class="red"><p>子页面信息</p><button id='btn'>向父传参</button><div id="p"></div></div><script>var btn = document.querySelector('#btn')btn.addEventListener('click', function (e) {// 子页面向父传参数window.parent.postMessage({ a: '子页面传给父页面的' }, '*')// window.open('https://www.baidu.com/')})var p = document.querySelector('#p')//子页面接收父页面的参数window.addEventListener('message', function (e) {p.innerHTML = e.data.b})</script></body></html>
