SoFunction
Updated on 2025-03-10

Detailed explanation of the method of implementing cross-tab page communication in JavaScript

Channel API (mainstream recommendation)

The Broadcast Channel API allows real-time communication between different tabs without using timer polling. You can create a shared Broadcast Channel and send messages between tabs. This way, when other tabs receive messages, they can respond immediately. The Broadcast Channel API provides a more reliable and efficient way to communicate across tabs, avoiding unnecessary polling and performance overhead.

First, we create a file crossTagMsg

const channel = new BroadcastChannel('sync-update')


export function sendMsg(type: any, content: any) {
    ({
        type,
        content
    });
}    

export function listenMsg(callback: (arg0: any) => any) {
    const handler = (e: { data: any; }) => {
        callback&&callback();
    }
    ('message',handler)
    return ()=>{
        ('message', handler) 
    }
}

Very simple two lines of code, one sends and one listens, and listens returns a removal function

Just refer to the function in the page

import {listenMsg,sendMsg} from '@/utils/crossTagMsg'

const send = ()=>{
    sendMsg('send',{name:'send'})
}

const unmountedListenMsg = listenMsg((info:any)=>{
    ()
})

onUnmounted(unmountedListenMsg)

()

()The method allows cross-domain communication between different tab pages and is a secure way to achieve cross-tab communication. The following is the use()Basic steps for cross-tab communication:

On the tab page of sending the message (sender):

// Send a message to the destination tabconst targetWindow = ('The URL of the target tab', '_blank'); // Open the target tab('Hello from sender', 'The source of the target tab');

// Listen to response messages from the target tab('message', function(event) {
  if ( === targetWindow) {
    ('Received response:', );
  }
});

On the tab page of the receiving message (receiver):

// Listen to messages from the sender's tab page('message', function(event) {
  if ( === 'Send party tab source') {
    ('Received message:', );

    // Send a response message to the sender's tab page    ('Hello from receiver', );
  }
});

In the above code, the sender's tab page is used()Method to open the target tab and use()Send a message to the destination tab. In the receiver tab, use()Listen to messages from the sender's tab page and send a response message after receiving the message.

existpostMessage()In the method, the first parameter is the data to be sent, which can be strings, numbers, objects, etc. The second parameter is the origin of the target window, which specifies the source of the receiver's tab page. This is to ensure that only messages from the specified source are received and processed to provide security.

It should be noted that in order to ensure security, a trust relationship is needed between the two tabs of communication, i.e., ensuring that the source of the target tab is what you expect and that messages from unknown or distrusted sources are not accepted.

By using()Method, you can communicate across domains between different tabs and pass data and messages. This approach is suitable for scenarios where real-time communication or sharing data between different tabs is required.

Visibilitychange can monitor the status of the page, judge the display and hiding of the page, and re-request the latest data when the page is displayed.

('visibilitychange',function(e:any){
    if ( === 'visible') {
        // Page display        ('Page display');
        // Perform the operation when the page is displayed Update data    } else if ( === 'hidden') {
        // The page is hidden        ('Page Hide');
        // Perform the operation when the page is hidden    }
})

-Sent Events(SSE)

Server-Sent Events (SSE) is a technology used to implement real-time one-way communication between a client and a server. It allows the server to push data to the client without sending a request.

SSE is based on the HTTP protocol and uses a long polling mechanism. The client sends an HTTP request to the server, which remains open until the server has new data available or the connection timed out. When the server has new data, it sends the data to the client as a response to a persistent connection.

The key to using SSE is that the server needs to send data in special formats and follow the SSE specifications. The data sent by the server is organized into a series of events, each with an event type and data field. The client processes the received data by listening to the corresponding event type.

Here is an example using SSE:

Server-side code ():

const http = require('http');

((req, res) => {
  (200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive',
  });

  // Send events and data to the client  ('event: message\n');
  ('data: Hello, world!\n\n');

  // Simulate sending an event per second  setInterval(() => {
    ('event: message\n');
    (`data: Current time is ${new Date().toLocaleTimeString()}\n\n`);
  }, 1000);
}).listen(3000);

Client Code (JavaScript):

const eventSource = new EventSource('/stream');

('message', (event) => {
  const data = ;
  ('Received message:', data);
});

In the above example, the server creates an HTTP server when the client reaches/streamWhen the path makes a request, the server will respondContent-TypeSet totext/event-stream, means that this is an SSE connection. The server pushes data to the client by sending an event response consisting of "event" and "data" fields.

Client usageEventSourceObject to establish an SSE connection and handle the received events through an event listener. In the above example, the client listensmessageEvents and print data to the console when the event occurs.

SSE provides a simple and effective way to implement real-time data push from the server to the client, suitable for applications that require real-time updates to data, such as chat applications, real-time notifications, stock quotations, etc. It has lower latency and higher efficiency compared to traditional polling methods.

This is the article about the detailed explanation of the method of implementing cross-tab communication in JavaScript. For more related JavaScript cross-tab communication content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!