前端-iframe-通信
子页面
<script type="text/javascript">
window.parent.postMessage("子窗口向父窗口发送消息", "*");
window.onload = function() {
window.parent.ifrmLoaded('子窗口调用父窗口方法');
//防止自己的页面被别人嵌套,修改别人的父页面地址转向
if(window.parent!=window) {
console.log('页面被别人嵌套')
//window.parent.location="http://hqlong.com";//修改父级页面路径
//window.top.location="http://hqlong.com";//修改祖父页面路径
}
}
</script>
父页面
<iframe src="childiframe.html" id="ifrm"></iframe>
<script>
if (window.attachEvent) {
//IE8兼容方法
window.attachEvent('onmessage', function (message) {
console.log(message.data+':来自IE9-');
});
} else {
//IE9兼容方法
window.addEventListener('message', function (message) {
console.log(message.data+':来自IE9+');
});
}
function ifrmLoaded(info) {
console.log(info)//给子页面调用
}
document.getElementById('ifrm').onload = function() {
console.log('子页面加载完成')
}
var oFrm = document.getElementById('ifrm');
oFrm.onload = oFrm.onreadystatechange = function() {
if (this.readyState && this.readyState != 'complete'){
console.log('子页面(含跨域)加载完成')
return;
}else console.log('子页面(含跨域)加载中')
}
</script>
posted on 2020-07-17 16:02 xcc_20190625 阅读(155) 评论(0) 收藏 举报
浙公网安备 33010602011771号