LocalStorage will not work through protocols, so if a user opens your site on one tab using http and another tab using https, both of these tabs will see separate localStorage objects. Cookies do not have the same problem (they have other problems, for example, bloating the size of each HTTP request to your site).
The sample code below contains a map in which the key is a unique identifier for a browser tab, and the value is a timestamp indicating when the last tab confirmed that it was still open. The map is stored in a cookie. This is not an ideal approach - each tab is updated every 3 seconds, and not instantly, and there are race conditions (several tabs that update the same cookie), but depending on what you can do after that.
If you run this code only on a specific page that you (more or less) know when this page has been opened several times in the same browser. Or run it on every page of your website and find out when your website was opened on several tabs.
The cookie reader / writer code is omitted for brevity (but taken from fooobar.com/questions/984775 / ... ) and the cookie data is encoded using json for simplicity, but you get this idea.
If you run this code and view cookies using the FireBug cookie tab, you will see a cookie update when you open and close the tabs. In fact, something like warning the user when several tabs open, remains as an exercise for the reader.
var timePeriod = 3000; // 3 seconds function tabHandler() { // ensure the current window has an identifier set if (!window.name.match(/^MySite[0-9]{3}/)) { window.name = 'MySite' + Math.round(Math.random() * 1000); } // read in the state of all the tabs var tabCookie = readCookie('tabs') || null; var tabs = JSON.parse(tabCookie) || {}; // update the timestamp for the current tab var now = (new Date()).getTime(); tabs[window.name] = now; // remove tab details that haven't had their timestamp updated var tooOld = timePeriod * 2; for (var tabKey in tabs) { if ((now - tabs[tabKey]) > tooOld) { delete tabs[tabKey]; } } // write back the current state of tabs createCookie('tabs', JSON.stringify(tabs), 1); setTimeout(tabHandler, timePeriod); } setTimeout(tabHandler, timePeriod);
Jamie source share