父页面
html1.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>模拟sso的系统</title>
<style>
.wrapper {
width: 100vw;
height: 100vh;
background-color: #f7f7f7;
position: relative;
}
.login {
width: 410px;
height: 498px;
border: 1px solid #ccc;
position: absolute;
right: 300px;
top: 50%;
transform: translateY(-50%);
}
</style>
</head>
<body>
<div class="wrapper">
<div class="login">
<iframe src="./html2.html" width="100%" height="100%" frameborder="0" id="iframe" onload="toChild()"></iframe>
</div>
</div>
<script>
window.onmessage = function(data) {
console.log('接收消息',data)
// localStorage.setItem('token', data)
// window.location.href = '/home'
}
// myframe.onload = function () { //注意要onload之后,才可以用postMessage
// let iframeWindow = myframe.contentWindow;
// iframeWindow.postMessage("宁静致远", "http://127.0.0.1:1002/1002.html");
// }
// //监听B传递的信息
// top.onmessage = function (ev) {
// console.log(ev.data);
// }
function toChild(){
let id = document.getElementById('iframe')
id.contentWindow.postMessage({themeColor:'#F57F3D'},'*')
}
</script>
</body>
</html>
子页面
html2.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>
html{
width: 100vw;
height: 100vh;
}
</style>
</head>
<body>
<!-- 可以选择用百分比;或者rem -->
<div class="login">
<div style="width: 70%">标题</div>
<input type="text">
<input type="text">
<button onclick="handleclick()">登录</button>
</div>
<script>
function handleclick() {
console.log('发送消息')
window.parent.postMessage('message', '*')
}
window.addEventListener('message', (event) => {
// main发过来的消息通过event.data接收
let dataFromMain = event.data
console.log(dataFromMain,'llll')
})
</script>
</body>
</html>