跨文档消息传送(cros-document Message),指的是在不同域的页面间传递消息。
以下是我用webstorm测试的使用postMessage在iframe和父级之间传参。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style type="text/css">
iframe{
width: 300px;
height: 300px;
}
</style>
</head>
<body>
<iframe src="http://localhost:63342/JQuery%E5%95%86%E5%9F%8E%E5%AE%9E%E4%BE%8B/iframe.html?_ijt=jrpcgmgcep8n6ppfh53s3fcttm" frameborder="1"></iframe>
<script>
console.log(window.location)
let iframe = document.querySelector("iframe")
iframe.onload=function () {
setTimeout(function () {
iframe.contentWindow.postMessage('WXS','http://localhost:63342')
},1000)
}
window.addEventListener("message",function (res) {
console.log(res)
})
</script>
</body>
</html>
但我发现这种方法好像并不能跨域,子父页面必须要在同域之下。即相同的协议(http),相同的域名(www.locaolhost),相同的端口号(63342)