Skip to content

Instantly share code, notes, and snippets.

@neevai
Created March 17, 2020 15:44
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 neevai/f3ed458577891c61e1c5c175e3d1f893 to your computer and use it in GitHub Desktop.
Save neevai/f3ed458577891c61e1c5c175e3d1f893 to your computer and use it in GitHub Desktop.
An Amplify.Storage class for Chrome extensions
/* global chrome */
const MEMORY_KEY_PREFIX = '@BackgroundStorage:';
let dataMemory = {};
export default class BackgroundStorage {
static syncPromise = null;
static setItem(key, value) {
chrome.runtime.sendMessage({action: 'store', subAction: 'setItem', key: MEMORY_KEY_PREFIX + key, value});
dataMemory[key] = value;
return dataMemory[key];
};
static getItem(key) {
return Object.prototype.hasOwnProperty.call(dataMemory, key) ? dataMemory[key] : undefined;
};
static removeItem(key) {
chrome.runtime.sendMessage({action: 'store', subAction: 'removeItem', key: MEMORY_KEY_PREFIX + key});
return delete dataMemory[key];
}
static clear() {
chrome.runtime.sendMessage({action: 'store', subAction: 'clear'});
dataMemory = {};
return dataMemory;
}
static sync() {
if (!BackgroundStorage.syncPromise) {
BackgroundStorage.syncPromise = new Promise((res, rej) => {
chrome.runtime.sendMessage({action: 'store', subAction: 'getAllKeys'}, messageResponse => {
const [response, error] = messageResponse;
if (error) rej(error);
const memoryKeys = response.filter((key) => key.startsWith(MEMORY_KEY_PREFIX));
chrome.runtime.sendMessage({action: 'store', subAction: 'multiGet', keys: memoryKeys}, messageResponse => {
const [response, error] = messageResponse;
if (error) rej(error);
Object.keys(response).forEach(key => {
const memoryKey = key.replace(MEMORY_KEY_PREFIX, '');
dataMemory[memoryKey] = response[key];
});
res();
});
});
});
}
return BackgroundStorage.syncPromise;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment