Frontend Development 8 min read

Cross‑Tab Communication with Drag‑and‑Drop Using BroadcastChannel in JavaScript

This article demonstrates how to implement cross‑tab communication in browsers by converting screen and client coordinates and using the BroadcastChannel API to synchronize draggable elements across multiple windows, complete with full HTML/JavaScript code examples.

Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
Cross‑Tab Communication with Drag‑and‑Drop Using BroadcastChannel in JavaScript

In the introduction the author notes a recent Twitter animation of particle interaction between browsers and proposes to recreate a similar effect using a draggable element that can move across multiple browser windows.

The implementation focuses on two technical challenges: converting screen coordinates to window (client) coordinates and establishing cross‑tab communication.

First, the article provides two helper functions that translate screen coordinates to client coordinates and vice‑versa, taking the browser’s toolbar height into account:

// 屏幕坐标转换为窗口坐标
const screenToClient = (screenX, screenY) => {
  const clienX = screenX - window.screenX;
  const clienY = screenY - window.screenY - barHeight();
  return [clienX, clienY];
};

// 窗口坐标转换为屏幕坐标
const clientToScreen = (clienX, clienY) => {
  const screenX = clienX + window.screenX;
  const screenY = clienY + window.screenY + barHeight();
  return [screenX, screenY];
};

Next, a simple HTML page defines a fixed‑position .card element whose background color can be set via a URL parameter; mouse events are attached to enable dragging.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>跨标签通讯</title>
  </head>
  <style>
    .card {
      width: 300px;
      height: 300px;
      background-color: #f00;
      position: fixed;
      top: 100px;
      left: 100px;
    }
  </style>
  <body>
    跨标签通讯
    <div class="card">card</div>
  <script>
    const barHeight = () => window.outerHeight - window.innerHeight;
    const cardDom = document.querySelector(".card");
    cardDom.style.top = 100 + "px";
    cardDom.style.left = 100 + "px";
    cardDom.style.background =
      new URLSearchParams(window.location.search).get("color") || "red";

    window.onload = function () {
      cardDom.onmousedown = function (e) {
        cardDom.style.cursor = "pointer";
        let x = e.pageX - cardDom.offsetLeft;
        let y = e.pageY - cardDom.offsetTop;
        window.onmousemove = function (e) {
          cardDom.style.left = e.clientX - x + "px";
          cardDom.style.top = e.clientY - y + "px";
          // 发送消息
          const clientCoordinateX = e.clientX - x;
          const clientCoordinateY = e.clientY - y;
          const ScreenCoordinate = clientToScreen(
            clientCoordinateX,
            clientCoordinateY
          );
          sendMessage(ScreenCoordinate);
        };
        window.onmouseup = function () {
          window.onmousemove = null;
          window.onmouseup = null;
          cardDom.style.cursor = "unset";
        };
      };
    };
  </script>

To synchronize the card’s position between tabs the BroadcastChannel API is used. A channel named “myChannel” is created, messages are posted when the element moves, and incoming messages are converted back to client coordinates to update the card in the receiving tab.

// 创建 Broadcast Channel
const channel = new BroadcastChannel("myChannel");
// 监听消息
channel.onmessage = (event) => {
  // 处理接收到的消息
  console.log('接收',event)
};
// 发送消息
const sendMessage = (message) => {
  channel.postMessage(message);
};

The article then combines all pieces into a complete example that demonstrates real‑time cross‑tab dragging, coordinate conversion, and color changes, illustrating how browsers can communicate despite being separate tabs.

In summary, by converting coordinates and leveraging BroadcastChannel, developers can create interactive multi‑window experiences such as draggable objects that appear to move seamlessly from one tab to another.

frontendJavaScriptBrowser APIdrag-and-dropBroadcastChannelcross-tab communication
Rare Earth Juejin Tech Community
Written by

Rare Earth Juejin Tech Community

Juejin, a tech community that helps developers grow.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.