1

I was trying to communicate between two tabs opened in the same browser. Both of the tabs have different domain (page1.local and page2.local). I used the following code, but it is working only if the domains are same.

Page1.local

<!DOCTYPE html>
<html lang="eng">
 <head>
 <title>Page 1 - Tab 1</title>
 </head>
 <body>
 <h1>Page 1 - Tab 1</h1>
 <button onclick="sendMessage()">Send Message</button>
 <script>
 const channel = new BroadcastChannel("myChannel");
 channel.addEventListener("message", (event) => {
 console.log("Received message:", event.data);
 });
 function sendMessage() {
 channel.postMessage("Hello from Page 1 - Tab 1!");
 }
 </script>
 </body>
</html>

Page2.local

<!DOCTYPE html>
<html lang="eng">
 <head>
 <title>Page 2 - Tab 2</title>
 </head>
 <body>
 <h1>Page 2 - Tab 2</h1>
 <button onclick="sendMessage()">Send Message</button>
 <script>
 const channel = new BroadcastChannel("myChannel");
 channel.addEventListener("message", (event) => {
 console.log("Received message:", event.data);
 });
 function sendMessage() {
 channel.postMessage("Hi from Page 2 - Tab 2!");
 }
 </script>
 </body>
</html>

I don't want to use any third-party application for communication. Is there any alternative way to achieve this with JavaScript?

asked Jan 7, 2025 at 8:08
7
  • 2
    How are the two applications related? If one tab was opened by the other, you can communicate using Window.postMessage instead of BroadcastChannel.postMessage Commented Jan 7, 2025 at 8:17
  • 6
    The Broadcast Channel API allows basic communication between browsing contexts (that is, windows, tabs, frames, or iframes) and workers on the same origin. - source: documentation Commented Jan 7, 2025 at 8:22
  • 2
    lots of discussion here: Communication between tabs or windows including the option of using localStorage as a communication proxy. Commented Jan 7, 2025 at 8:38
  • 1
    @Prifulnath I didn't say window which is the current window. You'd need to get a reference to the other tab, e.g. using window.open or an embedded iframe. Commented Jan 7, 2025 at 9:14
  • 4
    @pilchard localStorage does not work across origins either Commented Jan 7, 2025 at 9:15

0

Know someone who can answer? Share a link to this question via email, Twitter, or Facebook.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.