-
-
Save westtrade/d2e253e1c710a72a59ec0034b12a23e9 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
const shortId = () => { | |
return ("0000" + (Math.random()*Math.pow(36,4) << 0).toString(36)).slice(-4) | |
}; | |
const TAB_ID = shortId(); | |
let lastMessageId = null; | |
const getStorage = () => { | |
try { | |
if ('localStorage' in window && window['localStorage'] !== null) { | |
return localStorage; | |
} | |
} catch (e) { | |
return false; | |
} | |
return false; | |
}; | |
const on = (type = 'message', messageReciever) => { | |
global.window.addEventListener("storage", (event) => { | |
if (event.key === type) { | |
const {data, id} = JSON.parse(event.newValue); | |
if (TAB_ID !== id && id) { | |
messageReciever(event, data); | |
} | |
} | |
}); | |
}; | |
const broadcast = (type, data = {}) => { | |
const storage = getStorage(); | |
if (storage) { | |
const eventData = { | |
id: TAB_ID, | |
messageId: shortId(), | |
data | |
}; | |
storage.setItem(type, JSON.stringify(eventData)); | |
} else { | |
console.error('Local storage dosn\'t support!'); | |
} | |
}; | |
const get = (type, defaultData = {}) => { | |
const storage = getStorage(); | |
const eventData = storage.getItem(type); | |
const {data = defaultData} = JSON.parse(eventData) || {}; | |
return data; | |
}; | |
module.exports = { | |
getStorage, | |
on, | |
broadcast, | |
get, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment