electron/lib/renderer/extensions/storage.js

60 lines
1.2 KiB
JavaScript
Raw Normal View History

2016-06-09 23:39:24 +00:00
const getStorage = () => {
2016-06-09 21:14:14 +00:00
const data = window.localStorage.getItem('__chrome.storage.sync__')
if (data != null) {
return JSON.parse(data)
} else {
return {}
}
}
const setStorage = (storage) => {
const json = JSON.stringify(storage)
window.localStorage.setItem('__chrome.storage.sync__', json)
}
module.exports = {
sync: {
get (keys, callback) {
const storage = getStorage()
2016-06-09 23:26:42 +00:00
if (keys == null) return storage
let defaults = {}
switch (typeof keys) {
case 'string':
keys = [keys]
break
case 'object':
if (!Array.isArray(keys)) {
defaults = keys
keys = Object.keys(keys)
}
2016-06-09 23:39:24 +00:00
break
2016-06-09 23:26:42 +00:00
}
2016-06-09 23:39:24 +00:00
if (keys.length === 0) return {}
2016-06-09 21:14:14 +00:00
let items = {}
keys.forEach(function (key) {
2016-06-09 23:26:42 +00:00
var value = storage[key]
if (value == null) value = defaults[key]
items[key] = value
2016-06-09 21:14:14 +00:00
})
setTimeout(function () {
callback(items)
})
},
set (items, callback) {
const storage = getStorage()
Object.keys(items).forEach(function (name) {
storage[name] = items[name]
})
setStorage(storage)
setTimeout(callback)
}
}
}