iframe数据传递
- 总结了3中,跨域传递、同域传递、同源传递;
- 跨域传递访问document.getElementById(‘frameObj’).contentDocument为null,访问 document.getElementById(‘frameObj’).contentWindow都是只读,不能够操作;
- 同域传递、同源传递可以通过 document.getElementById(‘frameObj’).contentDocument、 document.getElementById(‘frameObj’).contentWindow,访问到iframe内部,等同与内部的document和window,可以访问DOM,修改内部变量;
跨域传递
<body>
<h2>容器父页面</h2>
<div>
<button class="test-button">我是按钮</button>
</div>
<div>
<iframe id="frameObj" src="http://127.0.0.1:8088/frame.html" frameborder="0" width="800px" height="700px"></iframe>
</div>
</body>
<script>
/**
* 说明:
* 容器父页面访问地址:http://192.168.1.1:8099/container.html
* 容器子页面访问地址:http://127.0.0.1:8088/frame.html
* 域名不同,通过postMessage进行跨域访问
*/
// 容器父页面js代码
document.querySelector('.test-button').addEventListener('click', () => {
// * 表示向所有的iframe发送信息,指定url,就可以定向发送信息
document.getElementById('frameObj').contentWindow.postMessage("向iframe中传递消息", "*")
})
</script>
<body>
<h2>子页面</h2>
<div id='message'> </div>
</body>
<script>
// iframe 子页面js代码
window.addEventListener('message', function (event) {
// 接收到容器页面传递到数据
console.log('event: ', event);
document.getElementById('message').innerHTML = "收到" + event.origin + "消息:" + event.data;
}, false);
</script>
同域传递
<body>
<h2>容器父页面</h2>
<div>
<button class="test-button">我是按钮</button>
</div>
<div>
<iframe id="frameObj" src="http://127.0.0.1:8088/frame.html" frameborder="0" width="800px" height="700px"></iframe>
</div>
</body>
<script>
/**
* 说明:
* 容器父页面访问地址:http://127.0.0.1:8099/container.html
* 容器子页面访问地址:http://127.0.0.1:8088/frame.html
* 域名相同,端口不同,
* document.domain可以设置成域名,一级域名、二级域名都可以
*/
// 容器父页面js代码
document.domain = '127.0.0.1'; // 相同的域名
document.querySelector('.test-button').addEventListener('click', () => {
// * 表示向所有的iframe发送信息,指定url,就可以定向发送信息
const childFrame = document.getElementById('frameObj').contentDocument
childFrame.getElementById('message').innerHTML = '接收到父组件传递到数据了'
})
</script>
<body>
<h2>子页面</h2>
<div id='message'> </div>
</body>
<script>
// iframe 子页面js代码
document.domain = '127.0.0.1'; // 相同的域名
</script>
同源传递
<body>
<h2>容器父页面</h2>
<div>
<button class="test-button">我是按钮</button>
</div>
<div>
<iframe id="frameObj" src="./frame.html" frameborder="0" width="800px" height="700px"></iframe>
</div>
</body>
<script>
/**
* 说明:
* 容器父页面访问地址:http://127.0.0.1:8088/container.html
* 容器子页面访问地址:http://127.0.0.1:8088/frame.html
* 域名、端口都相同
*/
// 容器父页面js代码
document.querySelector('.test-button').addEventListener('click', () => {
// * 表示向所有的iframe发送信息,指定url,就可以定向发送信息
const childFrame = document.getElementById('frameObj').contentDocument
childFrame.getElementById('message').innerHTML = '接收到父组件传递到数据了'
})
</script>
<body>
<h2>子页面</h2>
<div id='message'> </div>
</body>