Skip to content

Instantly share code, notes, and snippets.

@westtrade
Created May 17, 2017 10:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save westtrade/d2e253e1c710a72a59ec0034b12a23e9 to your computer and use it in GitHub Desktop.
Save westtrade/d2e253e1c710a72a59ec0034b12a23e9 to your computer and use it in GitHub Desktop.
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