As suggested in the comments, you can use local Storage/Session Storage to make this check. I’ll give a very simple example:
- Check if there is a count; if there is no count, start from
1
, otherwise increases what is there;
- Listen for events on Storage; if the count has changed, it is because there is another page trying to change it at the same time;
- If the page that is trying to change it "arrived first" (i.e. has a lower count), then it is the one who is in charge. Withdraw...
- If the page that is trying to change it "came later" (i.e. has a higher count), then the current page is in charge. Reset 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 this reply in a new tab and have the code executed, the alert will be displayed (It doesn’t seem to work on Stacksnippets, the code is on a iframe
Sandboxed that does not allow allow-same-origin
... No jsFiddle worked, meanwhile...).
(Note: when a page changes the Storage, an event is triggered in all others pages of the same origin. A own page that altered does not receive any event.)
Change the part where there is the alert
to do something else (like close the tab with window.close
). You can greatly improve the code above - for example, by making it 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 little more complex...
That said, for your particular case I suggest dealing with these "communication errors" instead of requiring only one tab to be open - if the user tries to access your account in two browsers Different, 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.
Please avoid long discussions in the comments; your talk was moved to the chat
– Maniero