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?