2016-06-28 09:02:25 +00:00
|
|
|
const getStorage = (storageType) => {
|
|
|
|
const data = window.localStorage.getItem(`__chrome.storage.${storageType}__`)
|
2016-06-09 21:14:14 +00:00
|
|
|
if (data != null) {
|
|
|
|
return JSON.parse(data)
|
|
|
|
} else {
|
|
|
|
return {}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-06-28 09:02:25 +00:00
|
|
|
const setStorage = (storageType, storage) => {
|
2016-06-09 21:14:14 +00:00
|
|
|
const json = JSON.stringify(storage)
|
2016-06-28 09:02:25 +00:00
|
|
|
window.localStorage.setItem(`__chrome.storage.${storageType}__`, json)
|
2016-06-09 21:14:14 +00:00
|
|
|
}
|
|
|
|
|
2016-06-28 20:02:03 +00:00
|
|
|
const scheduleCallback = (items, callback) => {
|
|
|
|
setTimeout(function () {
|
|
|
|
callback(items)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2016-06-28 09:02:25 +00:00
|
|
|
const getStorageManager = (storageType) => {
|
|
|
|
return {
|
2016-06-09 21:14:14 +00:00
|
|
|
get (keys, callback) {
|
2016-06-28 09:02:25 +00:00
|
|
|
const storage = getStorage(storageType)
|
2016-06-28 20:02:03 +00:00
|
|
|
if (keys == null) return scheduleCallback(storage, callback)
|
2016-06-09 23:26:42 +00:00
|
|
|
|
|
|
|
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-28 20:02:03 +00:00
|
|
|
if (keys.length === 0) return scheduleCallback({}, callback)
|
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
|
|
|
})
|
2016-06-28 20:02:03 +00:00
|
|
|
scheduleCallback(items, callback)
|
2016-06-09 21:14:14 +00:00
|
|
|
},
|
|
|
|
|
|
|
|
set (items, callback) {
|
2016-06-28 09:02:25 +00:00
|
|
|
const storage = getStorage(storageType)
|
2016-06-09 21:14:14 +00:00
|
|
|
|
|
|
|
Object.keys(items).forEach(function (name) {
|
|
|
|
storage[name] = items[name]
|
|
|
|
})
|
|
|
|
|
2016-06-28 09:02:25 +00:00
|
|
|
setStorage(storageType, storage)
|
2016-06-09 21:14:14 +00:00
|
|
|
|
|
|
|
setTimeout(callback)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2016-06-28 09:02:25 +00:00
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
sync: getStorageManager('sync'),
|
|
|
|
local: getStorageManager('local')
|
|
|
|
}
|