Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save eduardoacskimlinks/c4c251503871888f850d2a93216671c4 to your computer and use it in GitHub Desktop.
Save eduardoacskimlinks/c4c251503871888f850d2a93216671c4 to your computer and use it in GitHub Desktop.
Wrapper for Chrome Local Storage API persistence for Chrome extensions
import _get from "lodash/get"
import _isArray from "lodash/isArray"
// Placeholder to fetch your cache version
// CACHE_VERSION allows to reset user data after a version upgrade if it's required
import { CACHE_VERSION } from "config"
export const loadState = (keys) => {
const promise = new Promise((resolve, reject) => {
chrome.storage.local.get(CACHE_VERSION, (items) => {
const err = chrome.runtime.lastError
if (err) {
reject(err)
} else {
let inStorage = {}
if (_isArray(keys)) {
keys.forEach((key) => {
inStorage[key] = _get(items, [CACHE_VERSION, key])
})
} else {
inStorage = _get(items, [CACHE_VERSION], {})
}
resolve(inStorage)
}
})
})
return promise
}
export const saveState = (state) => {
const promise = new Promise((resolve, reject) => {
chrome.storage.local.set({ [CACHE_VERSION]: state }, () => {
const err = chrome.runtime.lastError
if (err) {
reject(err)
} else {
resolve()
}
})
})
return promise
}
export const clearState = () => {
return chrome.storage.local.clear()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment