javascript postMessage给子页面发消息
发送消息页面
<!DOCTYPE html>
<html>
<head>
<title>demo</title>
<meta charset="utf-8" />
<script>
var childwin
const childname = "popup"
function openChild() {
childwin = window.open("b.html", childname)
}
function sendMessage(){
let msg = "hello world"
childwin.postMessage(msg, '*')
}
window.addEventListener("message", (event)=>{
console.log(event.data)
})
</script>
</head>
<body>
<form>
<fieldset>
<input type='button' id='btnopen' value='打开新页面' onclick='openChild()' />
<input type='button' id='btnSendMsg' value='发消息' onclick='sendMessage()' />
</fieldset>
</form>
</body>
接收并回复消息页面
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<style>
* {
margin: 0;
padding: 0;
}
</style>
<title>demo</title>
</head>
<body>
<video id="video" autoplay style="width: 100%; height: 100%; object-fit: fill"></video>
</body>
</html>
<script>
window.addEventListener("message", (event)=>{
if (event.data != "hello world") {
return
}
console.log(event.data)
event.source.postMessage("response", event.origin)
})
</script>