Skip to content

Instantly share code, notes, and snippets.

@sumitpore
Last active February 9, 2024 05:19
Show Gist options
  • Star 28 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save sumitpore/47439fcd86696a71bf083ede8bbd5466 to your computer and use it in GitHub Desktop.
Save sumitpore/47439fcd86696a71bf083ede8bbd5466 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();
@panlina
Copy link

panlina commented Oct 28, 2022

It's not synchronous. It just eliminates callbacks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment