3

I'm using this code published by Sasi Varunan here

<script type="text/javascript">
        // Broad cast that your're opening a page.
        localStorage.openpages = Date.now();

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

Code is working like charm - doing exactly what I want - detect if an application it's already open in another tab browser or even in another browser window.

From my understanding:

The very first time when the application is started the followings thinks happen:

  1. App set openpages key with Date.now() value.
  2. Because of 1. storage event listener start onLocalStorageEvent event.
  3. Because the openpages key exists, is setting page_available key with Date.now ()
  4. When the followings apps are started they find page_available key in storage (the second if) the alert is triggered and I can redirect them to an error page.

QUESTION:

If I close all the browser windows and restart the app in a new winwdow everything still works fine.

This is what I don't understand because the page_available key is persistent is still there in the storage (no one deleted) the app should go on the second if and that the alert ... but this is not happening.

Radu
  • 995
  • 12
  • 23
  • 1
    You can read more about `localstorage` [here](https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API) – Oram Nov 28 '18 at 15:47

2 Answers2

5

The very first time when the application is started the followings thinks happen:

  1. App set openpages key with Date.now() value.
  2. Because of 1. storage event listener start onLocalStorageEvent event.
  3. Because the openpages key exists, is setting page_available key with Date.now ()
  4. When the followings apps are started they find page_available key in storage (the second if) the alert is triggered and I can redirect them to an error page.

The entire idea here is to communicate between the tabs using the storage event that is being triggered every time you access localStorage.

So when the page loads it first access the openpages key to trigger the storage event with e.key == "openpages".

Only after that it registers the event listener. So 2 only happens when you load the page on a second tab. On the second tab the event is triggered and the event listener is registered. Because the storage event is triggered for all the tabs, the event listener of the first tab (which is already registered) is being executed.

Tab 1 is triggered by the storage event with e.key == "openpages" and gets into the first if. There it triggers the storage event by accessing page_available key.

At this point tab 2 event listener reacts to the storage event but this time with e.key == "page_available" and gets into the second if where it shows the alert.

Note that if you don't close the tabs and open more tabs, tab 3 will trigger the storage event for all other tabs and you will have multiple tabs with alerts.


Just for reference:

If you want to trigger the alert on the first tab and not the second one you can achieve it with this code:

// Broadcast that you're opening the page.
localStorage.openpage = Date.now();

var onLocalStorageEvent = function(e) {
  if (e.key == "openpage") {
    alert("One more page already open");
  }
};
window.addEventListener('storage', onLocalStorageEvent);

Read more about localStorage here.
Read more about addEventListener here.

Oram
  • 1,589
  • 2
  • 16
  • 22
  • 1
    Thank you sir! This was what I was looking for I don't like/want to use code I don't understand :) – Radu Nov 28 '18 at 16:27
  • Still there is a big difference between original code and yours. In the original code the alert is triggered in the second (newest window), in yours the alert is triggered in the first (original) window at least in my Chrome ..... – Radu Nov 28 '18 at 22:32
  • If you have a little time, I'm very interested to understand why is this difference? – Radu Nov 29 '18 at 06:33
  • 1
    Ok, it's something that I didn't notice. I updated my answer. Let me know if you have more questions. – Oram Nov 29 '18 at 07:14
  • I just wanted to understand WHY in the original code the alert is triggered in second tab and in yours in the first one. From what I understood until now, on the second instance the event is triggered twice once for localStorage.openpages = Date.now(); and second for localStorage.page_available = Date.now(); Thank you for all your time and patience. – Radu Nov 29 '18 at 07:56
  • Exactly. It is being triggered twice. The second time is to show the alert on the second tab (using the `page_available ` key). In my code it was only triggered once and that's why it shows the alert on the first tab. – Oram Nov 29 '18 at 08:00
1

After a restart of the browser window everything still works fine, and I don't understand why because the page_available key is still there in the storage

This is because localStorage has no expiration date which is opposite of sessionStorage. sessionStorage gets cleared once the browser is closed, but localStorage still remains.

You can still clear the localStorage by clearing the browser cache & cookies

Also this snippet localStorage.openpages = Date.now(); seems to be incorrect.

If you want to set a value in localStorage, do like this

localStorage.setItem('openpages',Date.now());
brk
  • 48,835
  • 10
  • 56
  • 78
  • Yes I know that, and exactly because of that openpages key will exist in localStorage after a browser restart and app should not start ... but is starting and working OK. – Radu Nov 28 '18 at 15:53
  • What I mean, is if I close all browser windows and start again the app it will work even that openpages key is there ..... – Radu Nov 28 '18 at 15:55
  • Once you find out the key exists in the localStorage just remove the key and redirect them. – sridhar Nov 28 '18 at 15:56
  • The code is super OK I don't understand why it is working after a browser restart ..... – Radu Nov 28 '18 at 16:01
  • OK, exactly because openpages key is still there .... After a restart of the browser app should'nt go also on the second if and start the alert? This is what I don't underdstand ... – Radu Nov 28 '18 at 16:08
  • 1
    The first time the page loads the event listener is not registered yet. That's why it doesn't show the alert. – Oram Nov 28 '18 at 16:12
  • OK sir, Thank you! I will read more about event listeners to fully understand your answer. If you want post like an answer and I will immediately accept it. – Radu Nov 28 '18 at 16:15