0

is there a way to check if the user has more than one tab open (not globally, only on my website) or how many tabs the user has open? In the best case i need the amount but a boolean value would be enough. I need a solution in vanilla JavaScript (ES6) without jQuery or something else.

Thank you in advance.

Tim
  • 143
  • 2
  • 12
  • Possible duplicate of [Is there any way to count number of tabs are opened in chrome?](https://stackoverflow.com/questions/42109296/is-there-any-way-to-count-number-of-tabs-are-opened-in-chrome) – Isaac May 23 '18 at 08:19
  • I have a website that does scheduled tasks. JavaScript only. Any additional instance would cause errors. Currently I use LocalStorage and "unload"-Events to provide this functionality. But I thought there is possably a easier / better way. – Tim May 23 '18 at 08:20
  • 1
    @Isaac not exactly a duplicate, since the question you linked is about checking the total amount of tabs opened, which is (most likely) impossible, whereas checking the number of tabs on the current domain is not. – Delvian May 23 '18 at 08:36
  • @Delvian: guess I've misunderstood the question. disclaimer: im not the downvoter – Isaac May 23 '18 at 08:38

1 Answers1

1

You could create an ID for every opened tab and save it in an array in the localStorage (document.cookie would also work, but requires a bit more effort with getting and setting):

var tabId = Math.random();
var tabs = JSON.parse(localStorage.getItem('tabs')) || [];
tabs.push(tabId);
localStorage.setItem('tabs', JSON.stringify(tabs));

Now, to check how many tabs we have open on the current domain, we check the length of the tabs array in the localStorage:

function getTabCount()
{
    return JSON.parse(localStorage.getItem('tabs')).length;
}

Now, you can use getTabCount() to get the amount of tabs that are currently open.

Finally, we need to make sure our tabId is removed from the array when we close it:

window.addEventListener('beforeunload', function(e)
{
    tabs = JSON.parse(localStorage.getItem('tabs'));
    var index = tabs.indexOf(tabId);
    if (index !== -1)
        tabs.splice(index, 1);
    localStorage.setItem('tabs', JSON.stringify(tabs));
});

Do keep in mind that you need to keep using getTabCount() to check if any tabs have been opened or closed since you last used it.

Delvian
  • 185
  • 8