Detect multiple tabs opened at the same time – Javascript

If you have used WhatsApp Web, you may encounter a situation where if you open the web.whatsapp.com in multiple tabs in the same browser, you will get the error that “it is already being opened in another tab”. So in this article, we are going to teach you how you can detect multiple tabs opened at the same time using vanilla Javascript.

This is done for various reasons, top of the most is security. So how you can add this feature to your website ? The following code will display an alert message if a 2nd tab is opened at the same time:

<script>
    // Broadcast that you're opening a page.
    localStorage.openpages = Date.now();
    window.addEventListener('storage', function (e) {
        if(e.key == "openpages") {
            // Listen if anybody else is opening the same page!
            localStorage.page_available = Date.now();
        }
        if(e.key == "page_available") {
            alert("One more page already open");
        }
    }, false);
</script>

window.addEventListener(‘storage’, function (e) {});” This listener will be called only when the local storage value is updated from an external source, which means the other tab has made any changes in the local storage.

[do_widget id=custom_html-4]

How it works:

You might need to read the following steps 2 or 3 times to grab the concept properly.

  1. When you open the 1st tab, line # 3 will create a local storage value named “openpages”.
  2. Storage listener will NOT be called because the local storage value is updated from this tab.
  3. When you open the second tab, line # 3 will also create a local storage value named “openpages”.
  4. Storage listener from the 1st tab will be called because the local storage is updated from the 2nd tab.
  5. 1st tab will receive the value of “e.key” as “openpages”.
  6. So it will create another local storage value “page_available” at line # 7.
  7. Now this will call the storage listener from the 2nd tab. Because for the 2nd tab, it is called from the 1st tab.
  8. 2nd tab will receive the value of “e.key” as “page_available”, so it will display an alert message.

That’s how you can detect multiple tabs opened by the user at the same time. Let me know if you have any problem understanding this.

One Reply to “Detect multiple tabs opened at the same time – Javascript”

  1. It’s difficult to find knowledgeable people in this particular subject, however, you seem
    like you know what you’re talking about! Thanks

Comments are closed.