Check if user has opened 2 tabs at the same time - Javascript

Check if user has opened 2 tabs 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”.

This is done for various reasons, top of the most is security. So how you can add this feature in your website ? 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.

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.

Let me know if you have any problem understanding this.

Leave a Reply

Please disable your adblocker or whitelist this site!