如果你有使用iframe,那么肯定使用过或听过postMessage。这个API并没什么难度可言,就是一般很少使用,等到需要用时又容易忘记怎么使用,在此做个备忘吧。
父窗口文件:iframe_parent.html
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>*{
margin: 0;padding: 0;}</style>
</head>
<body><h6>父窗口</h6><div><input id="input" type="text"><button id="send">发消息给子窗口</button></div><p>子窗口的消息:<span id="message"></span></p><br><iframe id="iframe" src="iframe_child.html" frameborder="1"></iframe><script>const $ = (s) => {
return document.querySelector(s)}const btn = $('#send')const input = $('#input')const message = $('#message')const iframe = $('#iframe')btn.onclick = () => {
const data = input.valuedata && sendMessage(data)}function sendMessage(data) {
iframe && iframe.contentWindow.postMessage(data)}window.addEventListener('message', (event) => {
message.innerHTML = event.data// 此处不能再给子窗口发消息,不然会死循环// event.source.postMessage(`收到${event.data}了`)})</script>
</body>
</html>
子窗口文件 iframe_child.html
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>*{
margin: 0;padding: 0;}body{
background: #eee;}</style>
</head>
<body><h6>子窗口</h6><div><input id="input" type="text"><button id="send">发消息给父窗口</button></div><p>父窗口的消息: <span id="message"></span></p><script>const $ = (s) => {
return document.querySelector(s)}const btn = $('#send')const input = $('#input')const message = $('#message')const parent = window.parentbtn.onclick = () => {
const data = input.valuedata && sendMessageToParent(data)}window.addEventListener('message', (event) => {
console.log('父窗口===', event.source)console.log('来自父窗口的消息===', event.data)message.innerHTML = event.dataevent.source.postMessage(`收到(${
event.data})了`)})function sendMessageToParent (data) {
parent && parent.postMessage(data)}</script>
</body>
</html>
参考
- window.postMessage:https://developer.mozilla.org/zh-CN/docs/Web/API/Window/postMessage