Sometimes, we want to check if a website is open in another tab with JavaScript.
In this article, we’ll look at how to check if a website is open in another tab with JavaScript.
How to check if a website is open in another tab with JavaScript?
To check if a website is open in another tab with JavaScript, we use the BroadcastChannel
constructor.
For instance, we write
const bc = new BroadcastChannel("my-awesome-site");
bc.onmessage = (event) => {
if (event.data === `is-open`) {
bc.postMessage(`yes`);
alert(`Another tab of this site just got opened`);
}
if (event.data === `yes`) {
alert(`An instance of this site is already running`);
}
};
bc.postMessage(`is-open`);
to create a BroadcastChannel
on our site.
Then we set is onmessage
property to a function that checks for messages with event.data
.
We call postMessage
to send data to all the tabs.
If onmessage
is called, this means at least 1 tab is open.
Conclusion
To check if a website is open in another tab with JavaScript, we use the BroadcastChannel
constructor.