2018-01-24 01:26:50 +01:00
|
|
|
// We should not rely on local storage in an extension!
|
|
|
|
// We should use this instead!
|
|
|
|
// https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/storage/local
|
|
|
|
|
|
|
|
const extension = require('extensionizer')
|
|
|
|
|
|
|
|
module.exports = class ExtensionStore {
|
|
|
|
constructor() {
|
|
|
|
this.isSupported = !!(extension.storage.local)
|
|
|
|
if (!this.isSupported) {
|
|
|
|
log.error('Storage local API not available.')
|
|
|
|
}
|
|
|
|
}
|
2018-03-08 23:10:28 +01:00
|
|
|
|
|
|
|
async get() {
|
|
|
|
if (!this.isSupported) return undefined
|
|
|
|
const result = await this._get()
|
|
|
|
// extension.storage.local always returns an obj
|
|
|
|
// if the object is empty, treat it as undefined
|
|
|
|
if (isEmpty(result)) {
|
|
|
|
return undefined
|
|
|
|
} else {
|
|
|
|
return result
|
|
|
|
}
|
2018-01-24 01:26:50 +01:00
|
|
|
}
|
2018-03-08 23:10:28 +01:00
|
|
|
|
|
|
|
async set(state) {
|
|
|
|
return this._set(state)
|
2018-01-24 01:26:50 +01:00
|
|
|
}
|
2018-03-14 18:49:54 +01:00
|
|
|
|
2018-03-14 18:59:47 +01:00
|
|
|
_get() {
|
2018-03-14 18:49:54 +01:00
|
|
|
const local = extension.storage.local
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
local.get(null, (result) => {
|
|
|
|
const err = extension.runtime.lastError
|
|
|
|
if (err) {
|
|
|
|
reject(err)
|
|
|
|
} else {
|
|
|
|
resolve(result)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2018-03-14 18:59:47 +01:00
|
|
|
_set(obj) {
|
2018-03-14 18:49:54 +01:00
|
|
|
const local = extension.storage.local
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
local.set(obj, () => {
|
|
|
|
const err = extension.runtime.lastError
|
|
|
|
if (err) {
|
|
|
|
reject(err)
|
|
|
|
} else {
|
|
|
|
resolve()
|
|
|
|
}
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
2018-01-24 01:26:50 +01:00
|
|
|
}
|
2018-03-08 23:10:28 +01:00
|
|
|
|
|
|
|
function isEmpty(obj) {
|
2018-03-08 23:55:35 +01:00
|
|
|
return Object.keys(obj).length === 0
|
2018-03-08 23:10:28 +01:00
|
|
|
}
|