Skip to content

Instantly share code, notes, and snippets.

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 fhefh2015/cc1a2c8c85a7ad6cce0cd6e33a67ab7c to your computer and use it in GitHub Desktop.
Save fhefh2015/cc1a2c8c85a7ad6cce0cd6e33a67ab7c to your computer and use it in GitHub Desktop.
Chrome's Local StorageArea API in Synchronous way for use in Chrome extensions. Replace 'chrome.storage.local' by 'chrome.storage.sync' if you want to use Sync StorageArea
/**
* Retrieve object from Chrome's Local StorageArea
* @param {string} key
*/
const getObjectFromLocalStorage = async function(key) {
return new Promise((resolve, reject) => {
try {
chrome.storage.local.get(key, function(value) {
resolve(value[key]);
});
} catch (ex) {
reject(ex);
}
});
};
/**
* Save Object in Chrome's Local StorageArea
* @param {*} obj
*/
const saveObjectInLocalStorage = async function(obj) {
return new Promise((resolve, reject) => {
try {
chrome.storage.local.set(obj, function() {
resolve();
});
} catch (ex) {
reject(ex);
}
});
};
/**
* Removes Object from Chrome Local StorageArea.
*
* @param {string or array of string keys} keys
*/
const removeObjectFromLocalStorage = async function(keys) {
return new Promise((resolve, reject) => {
try {
chrome.storage.local.remove(keys, function() {
resolve();
});
} catch (ex) {
reject(ex);
}
});
};
export {
getObjectFromLocalStorage,
saveObjectInLocalStorage,
removeObjectFromLocalStorage
}
import { getObjectFromLocalStorage, saveObjectInLocalStorage, removeObjectFromLocalStorage } from './chrome-local-storage-api.js';
async function sampleUse() {
let sampleObject = {
'key-one': 1,
'key-two': 'xyz'
};
await saveObjectInLocalStorage(sampleObject);
console.log(await getObjectFromLocalStorage('key-one'));
console.log(await getObjectFromLocalStorage('key-two'));
await removeObjectFromLocalStorage('key-two');
console.log(await getObjectFromLocalStorage('key-two'));
}
sampleUse();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment