感觉之前应该写过iframe的使用,但是可能就是简单的去调用父类的某个方法而已,现在的话改改,使用postmessage,感觉比较正式点,其实也是用parent啦,哈哈
关于postmessage的解释:无敌的mdn
直接上代码:
父html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<iframe src="myiframe.html"></iframe>
<button class="mysendbtn">按钮</button>
</body>
<script>
window.onmessage = function(e) {
console.log(e.data);
//接受到消息后直接给iframe设置一个消息
var url = document.location.origin + '/myiframe.html';
document.querySelector("iframe").contentWindow.postMessage("这个是由主页面发送到ifame的信息", "*");
}
document.querySelector(".mysendbtn").addEventListener("click",function(){
document.querySelector("iframe").contentWindow.postMessage("这个是通过按钮点击向iframe发送信息", "*");
});
</script>
</html>
iframe页面:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
this is a iframe called iframe
</body>
</html>
<script>
window.parent.postMessage("这个是由iframe向父级页面发送信息", "*");
window.onmessage = function(e) {
console.log(e.data);
}
</script>
很简单,浑水摸鱼完了。记录下来,自己今后做整理用