Broadcast Channel API(不若差死拆no)

Broadcast Channel API vs postMessage API

方法

// 创建或加入某个频道
// 通过创建一个 BroadcastChannel 对象,一个客户端就加入了某个指定的频道。
// 只需要向 构造函数 传入一个参数:频道名称。如果这是首次连接到该广播频道,相应资源会自动被创建。

    // 连接到广播频道
    var bc = new BroadcastChannel('test_channel’);

// 发送消息

    // 发送简单消息的示例
    bc.postMessage('This is a test message.’);

// 接收消息

    // 简单示例,用于将事件打印到控制台
    bc.onmessage = function (ev) { console.log(ev); }

// 断开连接

    // 断开频道连接
    bc.close()

示例

// 父页面
var BroadcastChanne1 = new BroadcastChannel('load1');// 创建一个名字是load1的BroadcastChannel对象。记住这个名字,下面会用到
BroadcastChanne1.postMessage({
    value: $("#msg").val()
})

// 子页面
var BroadcastChanne1 = new BroadcastChannel('load1');//要接收到数据,BroadcastChannel对象的名字必须相同
BroadcastChanne1.onmessage = function(e){
    debugger;
    console.log(e.data);//发送的数据
};

同源页面间数据同步

<!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>
    <h3 id="title">你好,</h3>
    <input id="userName" placeholder="请输入你的用户名" />
  </body>
</html>
<script>
  const bc = new BroadcastChannel('abao_channel');

  (() => {
    const title = document.querySelector('#title');
    const userName = document.querySelector('#userName');

    const setTitle = (userName) => {
      title.innerHTML = '你好,' + userName;
    };

    bc.onmessage = (messageEvent) => {
      console.log(messageEvent)
      if (messageEvent.data === 'update_title') {
        setTitle(localStorage.getItem('title'));
      }
    };

    if (localStorage.getItem('title')) {
      setTitle(localStorage.getItem('title'));
    } else {
      setTitle('请告诉我们你的用户名');
    }

    userName.onchange = (e) => {
      const inputValue = e.target.value;
      localStorage.setItem('title', inputValue);
      setTitle(inputValue);
      bc.postMessage('update_title');
    };
  })();
</script>