利用BroadCastChannel进行浏览器同域通信(实现多开浏览器窗口卡片穿梭)

73 阅读1分钟

Broadcast Channel 是什么?

Broadcast Channel 会创建一个所有同源页面都可以共享的(广播)频道,因此其中某一个页面发送的消息可以被其他页面监听到。

如何使用?

创建

const bc = new BroadcastChannel('ceshi');

可以接受一个DOMString作为 name,用以标识这个 channel。在其他页面,可以通过传入相同的 name 来使用同一个广播频道。

发送数据

 bc.postMessage('信息发送内容');

数据接收

bc.onmessage = (event) => {
  console.log(event);
};

广播关闭

bc.close()

事例实操

<!DOCTYPE html>
<html>

<head>
  <title>postMessage</title>
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
  <style>
    :root{
      --img:url('https://img0.baidu.com/it/u=1260540201,2200335046&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500')
    }
    body{
      /* position: relative; */
      overflow: hidden;
    }
    .card{
      width: 150px;
      height: 200px;
      position: absolute;
      background: wheat;
      top: 0;
      left: 0;
      border-radius: 12px;
      font-size: 18px;
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      background: var(--img);
      background-size: 100% 100%;
      box-shadow: 3px 5px 4px 0px #0000004a;
    }
  </style>
</head>

<body>
<div class="card">
</div>
</body>

<script>
var box = document.querySelector('.card')

// A页面
const bc = new BroadcastChannel("test_channel");
bc.onmessage = (event) => {
  console.log(event);
  box.style.left = event.data.left-window.screenX + 'px'
  box.style.top =  event.data.top-window.screenY + 'px'
};
 bc.postMessage({left: window.screenX+box.style.left,top:window.screenY+box.style.top});

	
	// 绑定鼠标按下对象
	box.onmousedown = function() {

  // 获取鼠标在div上按下的位置
    var e = window.event;  //接收事件对象
	// 获取鼠标在当前事件源的位置
    var x1 = e.offsetX
    var y1 = e.offsetY
    
    // 绑定移动事件
    document.onmousemove = function() {
        // 获取鼠标在浏览器中的位置 - 每个事件都有自己独特的事件对象
        var e = window.event;
        var x2 = e.clientX
        var y2 = e.clientY
        
        // 计算left和top
        var l = x2 - x1
        var t = y2 - y1
    
        // 设置div的left和top
        box.style.left = l + 'px'
        box.style.top = t + 'px'
        bc.postMessage({left: window.screenX+l,top:window.screenY+t});
    }
}
// 拖拽行为一定要记得解绑mousemove事件
window.onmouseup = function() {
    document.onmousemove = null
}


</script>

</html>

运行效果

打开多个页面这张卡片可以穿梭于各个页面,里面就是用到图片相对屏幕的坐标通过BroadCastChannel进行广播通信

image.png