Tuesday, September 27, 2022

Detect multiple tabs open in vanilla javascript

<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>


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.

Ref:  https://adnan-tech.com/detect-multiple-tabs-opened-at-same-time-javascript/

No comments:

Post a Comment

Cybersecurity Essential: OpenSSL

In today’s digital landscape, securing data is paramount. Whether you’re building web applications, managing servers, or developing software...