美文网首页
跨文档消息传输-postMessage的使用

跨文档消息传输-postMessage的使用

作者: Huang_jing | 来源:发表于2020-02-12 16:15 被阅读0次

接收监听消息:

window.addEventListener("message", function() {...}, false);

发送窗口:

otherWindow.postMessage(message, targetOrigin);

页面A代码:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>跨域通信示例</title>
  <script type="text/javascript">
    // (1) 监听message事件
    window.addEventListener("message", function (ev) {
      // (2) 忽略指定URL地址之外的页面传过来的消息
      if (ev.origin != "http://127.0.0.1:5500") {
        return;
      }
      // (3) 显示消息
      document.getElementById("content").innerHTML = ("从" + ev.origin + "那里传过来的消息:\n\"" + ev.data + "\"");
    }, false);
    function hello() {
      var iframe = window.frames[0];
      // (4) 传递消息
      iframe.postMessage("你好", "http://127.0.0.1:5500/html5/test11-2.html");
    }
  </script>
</head>
<body>
  <div>页面A</div>
  <h1>跨域通信示例</h1>
  <div id="content"></div>
  <iframe width="400" src="http://127.0.0.1:5500/html5/test11-2.html" onload="hello()">
  </iframe>
</body>
</html>

页面B代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div>页面B</div>
    <div id="content"></div>
    <script>
        window.addEventListener("message", function(ev) {
            if (ev.origin != "http://127.0.0.1:8080") {
                return;
            }
            document.getElementById("content").innerHTML = "从"+ev.origin+"那里传来的消息<br>"+ev.data;
            ev.source.postMessage("你好,这里是"+this.location, ev.origin);
        }, false);
    </script>
</body>
</html>

效果图如下:

image.png

相关文章

网友评论

      本文标题:跨文档消息传输-postMessage的使用

      本文链接:https://www.haomeiwen.com/subject/tbdcfhtx.html