From 41d6ddd58868aff1c1e976b2f79115a06853ef81 Mon Sep 17 00:00:00 2001 From: Jessica Lord Date: Thu, 9 Jun 2016 14:14:14 -0700 Subject: [PATCH] Add storage file --- filenames.gypi | 1 + lib/renderer/chrome-api.js | 7 +--- lib/renderer/extensions/storage.js | 59 ++++++++++++++++++++++++++++++ 3 files changed, 61 insertions(+), 6 deletions(-) create mode 100644 lib/renderer/extensions/storage.js diff --git a/filenames.gypi b/filenames.gypi index 5f1fdc3b141f..891d28fada49 100644 --- a/filenames.gypi +++ b/filenames.gypi @@ -63,6 +63,7 @@ 'lib/renderer/api/remote.js', 'lib/renderer/api/screen.js', 'lib/renderer/api/web-frame.js', + 'lib/renderer/extensions/storage.js' ], 'js2c_sources': [ 'lib/common/asar.js', diff --git a/lib/renderer/chrome-api.js b/lib/renderer/chrome-api.js index 17c3f5bfbd1a..c614b8f1e468 100644 --- a/lib/renderer/chrome-api.js +++ b/lib/renderer/chrome-api.js @@ -183,12 +183,7 @@ exports.injectTo = function (extensionId, isBackgroundPage, context) { onMessage: chrome.runtime.onMessage } - chrome.storage = { - sync: { - get () {}, - set () {} - } - } + chrome.storage = require('./extensions/storage.js') chrome.pageAction = { show () {}, diff --git a/lib/renderer/extensions/storage.js b/lib/renderer/extensions/storage.js new file mode 100644 index 000000000000..07080ee30b07 --- /dev/null +++ b/lib/renderer/extensions/storage.js @@ -0,0 +1,59 @@ + +const getStorage = () => { + 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() + + if (keys === {} || keys === []) return {} + if (keys === null) return storage + + if (typeof keys === 'string') keys = [keys] + + let items = {} + // ['foo'] or ['foo', 'bar'] or [{foo: 'bar'}] + keys.forEach(function (key) { + if (typeof key === 'string') { + items[key] = storage[key] + } + else { + const objKey = Object.keys(key) + if (!storage[objKey] || storage[objKey] === '') { + items[objKey] = key[objKey] + } else { + items[objKey] = storage[objKey] + } + } + }) + + setTimeout(function () { + callback(items) + }) + }, + + set (items, callback) { + const storage = getStorage() + + Object.keys(items).forEach(function (name) { + storage[name] = items[name] + }) + + setStorage(storage) + + setTimeout(callback) + } + } +}