14.3 跨域 - postMessage
前端
a.html
<iframe src="http://localhost:4000/b.html" frameborder="0" id="frame" onload="load()"></iframe> <script> function load() { const frame = document.getElementById('frame') frame.contentWindow.postMessage('我爱你', 'http://localhost:4000') // 要加上发送的域 window.onmessage = e => { console.log(e.data) } } </script>
b.html
<script> window.onmessage = e => { console.log(e.data) e.source.postMessage('我不爱你', e.origin) } </script>
后端
a.js
let express = require('express') let app = express() app.use(express.static(__dirname)) app.listen(3000)
b.js
let express = require('express') let app = express() app.use(express.static(__dirname)) app.listen(4000)