Created
February 7, 2017 18:54
-
-
Save caseyWebb/5c77a50a8d3dc254864ca0856f2972ad to your computer and use it in GitHub Desktop.
Shared Tab Session
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
const { each } = require('lodash') | |
incrementTabCount() | |
window.addEventListener('unload', decrementTabCount) | |
window.addEventListener('storage', (e) => { | |
if (e.key === 'getSessionStorage') { | |
// Some tab asked for the sessionStorage | |
localStorage.setItem('sessionStorage', JSON.stringify(sessionStorage)) | |
localStorage.removeItem('sessionStorage') | |
} | |
}) | |
module.exports = { | |
initSessionFromOpenTabs() { | |
return new Promise((resolve) => { | |
function handler(e) { | |
if (e.key === 'sessionStorage') { | |
each(JSON.parse(event.newValue), (v, k) => sessionStorage.setItem(k, v)) | |
window.removeEventListener('storage', handler) | |
resolve() | |
} | |
} | |
window.addEventListener('storage', handler) | |
if (sessionStorage.length === 0 && getTabCount() > 1) { | |
// Ask other tabs for session storage | |
localStorage.setItem('getSessionStorage', Date.now()) | |
} else { | |
resolve() | |
} | |
}) | |
} | |
} | |
function getTabCount() { | |
return parseInt(localStorage.getItem('tabsOpen')) || 0 | |
} | |
function setTabCount(n) { | |
localStorage.setItem('tabsOpen', n) | |
} | |
function incrementTabCount() { | |
setTabCount(getTabCount() + 1) | |
} | |
function decrementTabCount() { | |
setTabCount(getTabCount() - 1) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment