Check if more site flaps X is open

2

Is it possible to check if my site is open more than once in the user's browser?

My site requires that only one tab be used to avoid communication error, so I need to alert the user when it opens more than one tab on my site, is there a possibility with JavaScript?

    
asked by anonymous 24.04.2015 / 05:31

1 answer

3

As suggested in the comments, you can use local storage / session storage to do this verification. I'll give you a simple example:

  • Checks if there is a count; if it does not exist, it starts from 1 , otherwise it increments what is there;
  • Listen for events in storage ; if the count has changed, it is because you have another page trying to change it at the same time;
    • If the page you are trying to change it "arrived first" (i.e. has a smaller count), then it is the one that is in charge. Retire ...
    • If the page that is trying to change it "arrived later" (i.e. has a larger count), then the current page is the one that orders it. Resets the count to its own value.
  • var contagem = +localStorage.getItem("contagem"); // Antigo dono
    window.addEventListener("storage", storageChanged, false);
    localStorage.setItem("contagem", contagem+1); // Tenta se tornar o novo dono
    
    function storageChanged(event) {
        if ( event.newValue <= contagem )    // Se o antigo dono ainda estiver por aí
            alert("Já tem uma aba aberta."); // Vai embora
        else                                              // Senão
            localStorage.setItem("contagem", contagem+1); // torna-se o novo dono
    }

    If you run the above code, nothing will happen. But if you open that response in a new tab and have the code executed, the alert will be displayed (It does not seem to work in StackSnippets, the code is in% sandboxed% allows iframe ... In jsFiddle it worked , meanwhile ...).

    ( Note: ) When a page changes to storage , an event is fired on all the other pages in the same source. > own page that changed does not receive any event.)

    Change the part where there is allow-same-origin to do something else (type close the alert ). You can improve the code above - for example, so that when the main tab is closed it passes the command to the next one in the queue (assuming the others remain open, only inactive) - but then it gets a bit more complex ...

    That said, for your particular case I suggest dealing with these "communication errors" instead of requiring that only one tab be open - if the user tries to access your account in two different browsers , for example , What would happen? Better design the system so that two open tabs do not cause problems, even if you have to rely on the help of the server.

        
    24.04.2015 / 07:28