H5PostMessages实现跨页面通信

效果图

H5PostMessages实现跨页面通信_第1张图片

postMessages

HTML5提供了新型机制PostMessage实现安全的跨源通信.

语法

otherWindow.postMessage(message, targetOrigin, [transfer]);
  • otherWindow: 其他窗口的一个引用, 比如IFRAME的contentWindow属性, 执行, window.open返回的窗口对象.
  • message: 将要发送到其他窗口的数据.
  • targetOrigin: 通过窗口的origin属性来指定哪些窗口能接收到消息事件, 其值可以是字符”*”(表示无限制)或者一个URL
  • transfer: 是一串和message同时传递的Transferable对象. 这些对象的所有权将被转移给消息的接收方, 而发送一放将不再保有所有权.

例子

//1.html消息发送端


<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>消息发送端title>
head>
<body>
  <script>
    (function () {
      //模拟数据
      let message = [
        'hi',
        'hello',
        'liuxuan',
        'jizemingbu',
        'daqiaoweijiu',
      ];
      //随机获取message信息, 真实环境是从服务端获取数据
      let getMessage = function () {
        let index = Math.floor(Math.random() * 10);
        return message[index] || null
      }

      let postMessageLoop = function () {
        let randomTime = Math.floor(Math.random() * 1000);
        setTimeout(() => {
          let message = getMessage();
          if (message !== null) {
            window.parent.postMessage(message, 'http://localhost:8088');
          }
          postMessageLoop();
        }, randomTime);
      }
      postMessageLoop();
    })()
  script>
body>
html>
//2.html 消息接收端


<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>消息接收端title>
head>
<body>
  <ul id="messageList">ul>
  <iframe id="postWindow" src="1.html" style="display:none">iframe>
  <script>
    (function (w) {
      let doc = w.document;
      let msgList = doc.querySelector('#messageList');
      let handler = function (msg) {
        let li = doc.createElement('li');
        li.innerText = msg;
        msgList.appendChild(li);//把消息显示
      }

      //监视postMessage发送的消息
      w.addEventListener('message', function (event) {
        if (event.origin === 'http://localhost:8088') {
          handler(event.data);
        }
      }, false);
    })(window)
  script>
body>
html>

你可能感兴趣的:(HTML,postmessag,H5跨页面通信)