<div class="login">
<form >
<div class="form-item">
<label for="username"> 用户名:</label>
<input type="text" name="username" id="username" placeholder="请输出用户名">
</div>
<div class="form-item">
<label for="password"> 明码:</label>
<input type="text" name="password" id="password" placeholder="请输出明码">
</div>
<div class="form-item">
<input type="submit" value="登录">
</div>
</form>
</div>
<script>
// 监听父级传递过去的数据
window.addEventListener('message', function(e) {console.log('父 widonw 传递过去的数据:',JSON.parse(e.data));
})
const form = document.querySelector('form');
form.addEventListener('submit', function(e) {e.preventDefault();
// 获取用户名
const username = document.querySelector('#username').value;
// 获取明码
const password = document.querySelector('#password').value;
window.parent.postMessage({username, password}, '*');
})
</script>
<body>
<iframe src="./login.html" id="iframeByLogin"></iframe>
<script>
// 监听子级传递过去的数据
window.addEventListener('message', function(e) {console.log('子(登录 iframe)传递过去的数据:',e.data);
})
const _iframeLogin = document.querySelector('#iframeByLogin');
_iframeLogin.onload = function() {
let param = {
username: 'admin',
password: '123456'
}
_iframeLogin.contentWindow.postMessage(JSON.stringify(param), '*');
}
</script>
</body>