Four ways to implement cross-tab page communication
We assume that our requirement is to open a new page and these two pages need to communicate, so we can use the following communication method
1. localStorage+storage event
principle: Shared using the same-origin tab page of the browser
localStorage
Storage data and passstorage
Event listening data changes.
<!-- src/views/ --> <template> <div> <h1>Home Page</h1> </div> </template> <script setup> import { onMounted } from "vue"; onMounted(() => { // Tag Page Home: Write data ("message", "Home Page"); }); </script>
localStorage
is a new session storage object added to HTML5. It allows web pages to store data in the form of key-value pairs in the browser, and this data will not disappear with the page closing unless manually deleted.
<!-- src/views/ --> <template> <div> <h1>About Page</h1> </div> </template> <script setup> import { onMounted } from "vue"; onMounted(() => { // Tag page About: Listen to changes ("storage", (event) => { if ( === "message") { ("Message received:", ); } }); }); </script>
-
In this way, when the page Home sets localStorage, it will be monitored, achieving a communication effect of different tags.
Pros and cons
✅ Easy to use, no server required
❌ Unable to listen to the current tab page modification, data needs to be serialized and transmitted.
⚠️ Note:sessionStorage
Cross-label events cannot be triggered because their data is shared only at the window level.Then someone will have problems, since
localStorage
Yes, thatsessionStorage
Is that okay? The answer is no.because
storage
The triggering conditions of the event are: whenlocalStorage
orsessionStorage
When the data in change, in addition to the window (or tab page) that triggers the change, other windows (or tab pages) under the same source will receivestorage
event.because
sessionStorage
The data of is at the window (or tab page) level, between different tab pagessessionStorage
isolated from each other, one tab page issessionStorage
The modifications will not affect other tabs, sosessionStorage
Changes will not trigger other tabsstorage
event.
2. BroadcastChannel API
principle :
BroadcastChannel
API is a new mechanism added to HTML5 to implement communication across windows, tabs and even worker threads in the browser. It provides a simple and effective way to allow different browsing contexts of the same origin (such as different windows, tabs,iframe
or Web Workers) can send and receive messages to each other.
<!-- src/views/ --> <template> <div> <h1>Home Page</h1> <el-button @click="sendMessage">Send a message</el-button> </div> </template> <script setup> const sendMessage = () => { // Tag Page Home: Send Message // 1. Create a BroadcastChannel instance // To use BroadcastChannel, you first need to create a BroadcastChannel instance and specify a channel name. The channel name is a string that identifies different communication channels. The channel here is "chat". const channel = new BroadcastChannel("chat"); // 2. Send a message // Use the postMessage method to send messages to the specified channel. The message can be any data type that can be serialized, such as strings, objects, arrays, etc. ("Home Message"); }; </script>
<!-- src/views/ --> <template> <div> <h1>About Page</h1> </div> </template> <script setup> import { onMounted } from "vue"; onMounted(() => { const channel = new BroadcastChannel("chat"); // 3. Receive message // Receive messages sent to the channel by other contexts by listening to the message event. = (event) => { ("Message received:", ); // Listen to messages }; }); </script>
-
This is a common communication method in modern projects. Use the BroadcastChannel API to send and listen to two pages separately.
Pros and cons
✅ Strong real-time, simple code
❌ IE browser not supported
⚠️ Pay attention to the fact that the channel name is globally unique to avoid conflicts.
3. WebSocket
principle: Full duplex communication is realized through server transfer messages.
<template> <div> <h1>WebSocket Example</h1> <el-button @click="connectWebSocket">connect WebSocket</el-button> <el-button @click="sendMessage" :disabled="!socket">Send a message</el-button> <el-button @click="closeWebSocket" :disabled="!socket">关闭connect</el-button> <ul> <li v-for="(message, index) in receivedMessages" :key="index"> {{ message }} </li> </ul> </div> </template> <script setup> import { ref } from "vue"; //Storing WebSocket instancesconst socket = ref(null); // Store the received messageconst receivedMessages = ref([]); // Connect to WebSocketconst connectWebSocket = () => { // Create a WebSocket instance. Take this as an example. It is a public WebSocket test server, which saves you the trouble of building a server by yourself. = new WebSocket("wss://"); // Triggered when the WebSocket connection is successful = () => { ("WebSocket connection is successful"); ("WebSocket connection is successful"); }; // Triggered when a server message is received = (event) => { ("Message received:", ); (); }; // Triggered when the WebSocket connection is closed = () => { ("WebSocket connection closed"); ("WebSocket connection closed"); = null; }; // Triggered when an error occurs in WebSocket = (error) => { ("An error occurred in WebSocket:", error); ("An error occurred in WebSocket"); }; }; // Send a message to the serverconst sendMessage = () => { if () { const message = "Hello, WebSocket!"; (message); (`Send a message: ${message}`); } }; // Close WebSocket connectionconst closeWebSocket = () => { if () { (); } }; </script>
-
In actual projects, the WebSocket server is generally built by the backend, and here is a public test server as an example.
Pros and cons
✅ Supports cross-domain and has high real-time performance
❌ The server needs to be maintained, with high complexity
⚠️ The actual project needs to build its own server to ensure security.
4. SharedWorker
principle: SharedWorke r is a special type of Worker that can be shared between multiple browser contexts (such as windows, iframes, etc.).
<template> <el-card> <template #header> <div class="card-header">SharedWorker Communication example</div> </template> <el-button @click="sendMessage" >Send a message to SharedWorker</el-button > <el-card v-if="response" style="margin-top: 20px"> <template #header> <div>Response content</div> </template> <div>{{ response }}</div> </el-card> </el-card> </template> <script setup> import { ref, onMounted } from "vue"; // Create a SharedWorker instance and specify the path of the worker thread script fileconst worker = new SharedWorker(""); //Storing the received responseconst response = ref(""); const sendMessage = () => { const message = "Hello, SharedWorker!"; // Send a message to SharedWorker (message); ("Send a message to SharedWorker:", message); }; onMounted(() => { // Listen to SharedWorker message events = function (event) { const newResponse = ; ("Received from SharedWorker:", newResponse); // Update the response content = newResponse; }; // Start port communication (); }); </script>
// Files need to be placed in public// Create a message channel for communication between different contexts and worker threads = function (e) { // Get port object for receiving and sending messages const port = [0]; // Listen to the message event on the port = function (event) { const message = ; ("SharedWorker received message:", message); // Reply to the message to the port where the message is sent const response = `SharedWorker Message received: ${message}`; (response); }; };
-
Notice:
Same Origin Policy:
SharedWorker
Follow the same origin strategy, i.e.The file must be of the same origin as the main page file (same protocol, domain name and port). If it is passed directly
file://
The protocol opens an HTML file, which will be caused by the same-origin policy restrictions.SharedWorker
Not working properly. If you want to test locally with html files, you need to start a server, and Live Server can meet the needs.File path: In Vue projects, usually
The file is placed
public
In the directory, because the files in the directory will not be processed by Webpack or vite, the path and name of the file will remain unchanged after construction, ensuring thatSharedWorker
Able to load script files correctly.compatibility:
SharedWorker
It is widely supported in modern browsers, but may not be supported in some older browsers. When using it, it is recommended to perform compatibility checks or use Polyfill to ensure compatibility in different browsers.Pros and cons
✅ No server required, support complex logic
❌ Limited compatibility (IE is not supported), difficult to debug
⚠️ Pay attention to the same-origin policy, and local testing requires starting the server.
These four common cross-tab page communications, and some of them are not commonly used, such as:postMessage
、ServiceWorker
。It is either more complicated or has obvious flaws, so I won't go into it here. Summarize the usage scenarios 👇
Scene | Recommended plan | reason |
---|---|---|
Simple data synchronization |
localStorage / BroadcastChannel
|
Lightweight and server-free |
Real-time communication |
BroadcastChannel / WebSocket
|
Event-driven or server push |
Cross-domain requirements | WebSocket |
Support cross-domain protocols |
Complex computing logic | SharedWorker |
Share the pressure of the main thread |
Compatibility priority |
localStorage + WebSocket
|
Coverage old browsers and cross-domain requirements |
The above is the detailed content of the four ways Vue3 can realize cross-tab page communication. For more information about cross-tab page communication, please pay attention to my other related articles!
Related Articles
Vue component parameter verification method and non-props feature
This article mainly introduces the methods of Vue component parameter verification and non-props features. The editor thinks it is quite good. I will share it with you now and give you a reference. Let's take a look with the editor2019-02-02vue router Explanation of the routing jump method
This article mainly introduces an overview of the route jump method of vue router. When using Vue, the most common thing we use is the Vue Router library that is equipped with Vue. This article will explain it in detail with the sample code. Friends who need it can refer to it.2022-12-12Example of using third-party icon library iconfont using ElementUI in Vue
This article mainly introduces the example of using ElementUI to use the third-party icon library iconfont in Vue. The editor thinks it is quite good. I will share it with you now and give you a reference. Let's take a look with the editor2018-10-10van-dialog pop-up window asynchronous closing function - verification form implementation
Sometimes we need to process form data through pop-up windows. There are many ways to implement it in native WeChat applets and vant components. Among them, the most beautiful UI is achieved through van-dialog nested forms. This article mainly introduces the asynchronous closing of van-dialog pop-up windows-checking form. Friends who need it can refer to it.2023-11-11Vue programmatic routing navigation implementation example
This article mainly introduces Vue programmatic routing navigation2022-04-04Detailed explanation of the modal box process of Vue handwritten dialog component
This article mainly introduces the modal box process of Vue handwritten dialog component. The dialog component is a modal box, so it should be fixedly positioned on the page, and a certain slot is required to allow the user to customize the display content.2023-02-02Learn the key knowledge that must be mastered in the Vue framework
This article mainly introduces the key knowledge that must be mastered in learning Vue. Students who want to understand Vue can refer to it.2021-04-04Various ways to introduce external scripts in Vue projects
In modern front-end development, we often need to use some third-party external scripts or libraries, especially maps, charts, analysis tools, etc. In Vue projects, there are many ways to introduce external scripts. This article will introduce in detail several common methods of introducing external scripts in Vue projects. Friends who need it can refer to it.2025-01-01Vue Custom Components v-model Detailed explanation
This article mainly introduces the use of Vue custom components v-model, including the use in vue2 and in vue3. This article introduces you very detailed through sample code, which has certain reference value for your study or work. Friends who need it can refer to it.2022-08-08Detailed explanation of the difference between mutations and actions in Vuex
Below, the editor will share with you a detailed explanation of the differences between mutations and actions in Vuex. It has good reference value and hope it will be helpful to everyone. Let's take a look with the editor2018-03-03