+
89
-

回答

BroadcastChannel API 可以在浏览器中进行跨窗口或跨标签页的通信。BroadcastChannel 允许同源的多个浏览器上下文(如窗口、标签页、iframe 等)之间进行消息传递。

以下是完整的代码示例,包括发送和接收消息的部分:

HTML 部分
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>BroadcastChannel Example</title>
</head>
<body>
    <input type="text" id="input" placeholder="Enter message">
    <button id="sendButton">Send Message</button>
    <div id="output"></div>

    <script>
        // 1. 创建 BroadcastChannel 实例
        const bc = new BroadcastChannel('my-channel');

        // 2. 发送消息
        const button = document.getElementById('sendButton');
        const input = document.getElementById('input');

        button.addEventListener('click', () => {
            bc.postMessage(input.value);
            input.value = ''; // 清空输入框
        });

        // 3. 接收消息
        bc.addEventListener('message', (e) => {
            const output = document.getElementById('output');
            output.textContent = `Received message: ${e.data}`;
        });
    </script>
</body>
</html>
解释

创建 BroadcastChannel 实例:

const bc = new BroadcastChannel('my-channel');

这行代码创建了一个名为 my-channel 的 BroadcastChannel 实例。所有使用相同频道名称的 BroadcastChannel 实例都可以相互通信。

发送消息:

button.addEventListener('click', () => {
    bc.postMessage(input.value);
    input.value = ''; // 清空输入框
});

当用户点击按钮时,输入框中的内容会被发送到 my-channel 频道。postMessage 方法用于发送消息。

接收消息:

bc.addEventListener('message', (e) => {
    const output = document.getElementById('output');
    output.textContent = `Received message: ${e.data}`;
});

当接收到消息时,message 事件会被触发。事件对象 e 包含一个 data 属性,表示接收到的消息内容。接收到的消息会被显示在页面的 output 元素中。

运行示例打开两个或多个浏览器标签页,加载相同的 HTML 页面。在一个标签页中输入消息并点击“Send Message”按钮。在其他标签页中,你会看到接收到的消息显示在页面上。注意事项BroadcastChannel 只能在同源的上下文之间进行通信。如果频道名称不同,不同的 BroadcastChannel 实例之间无法通信。BroadcastChannel 是一个相对较新的 API,可能不被所有浏览器完全支持。在使用之前,请确保检查浏览器的兼容性。

通过这种方式,你可以轻松地在多个浏览器上下文之间进行消息传递,适用于需要跨窗口或跨标签页通信的应用场景。

网友回复

我知道答案,我要回答