以下HTML在http://127.0.0.1:1001下运行,我们打算通过postMessage() 跨域与http://127.0.0.1:1002/1002.html进行通信:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>server1</h1>
<iframe id="myframe" src="http://127.0.0.1:1002/1002.html" frameborder="0"></iframe>
<script>
myframe.onload = function () { //注意要onload之后,才可以用postMessage
let iframeWindow = myframe.contentWindow;
iframeWindow.postMessage("宁静致远", "http://127.0.0.1:1002/1002.html");
}
//监听B传递的信息
window.onmessage = function (ev) {
console.log(ev.data);
}
</script>
</body>
</html>
这里需要注意,我们 发送方的引用,即调用postMessage() 那个引用的源要与接受方的源即postMessage()的第二的参数 要同源。否则会报以下错误: