Browse Source

Use a file as Chrome Storage rather than localStorage

Alexandre Lachèze 7 years ago
parent
commit
d2002ff3fc
1 changed files with 27 additions and 2 deletions
  1. 27 2
      lib/renderer/extensions/storage.js

+ 27 - 2
lib/renderer/extensions/storage.js

@@ -1,5 +1,30 @@
+const fs = require('fs')
+const path = require('path')
+const { remote } = require('electron')
+const { app } = remote;
+
+const getChromeStoragePath = (storageType) => {
+  return path.join(
+    app.getPath('userData'), `/Chrome Storage/${storageType}.json`)
+}
+const readChromeStorageFile = (storageType) => {
+  const filePath = getChromeStoragePath(storageType)
+  if(!fs.existsSync(filePath)) return null
+  return fs.readFileSync(filePath, 'utf8')
+}
+
+const writeChromeStorageFile = (storageType, data) => {
+  const filePath = getChromeStoragePath(storageType)
+  try {
+    fs.mkdirSync(path.dirname(filePath))
+  } catch (error) {
+    // Ignore error
+  }
+  return fs.writeFileSync(filePath, data)
+}
+
 const getStorage = (storageType) => {
-  const data = window.localStorage.getItem(`__chrome.storage.${storageType}__`)
+  const data = readChromeStorageFile(storageType)
   if (data != null) {
     return JSON.parse(data)
   } else {
@@ -9,7 +34,7 @@ const getStorage = (storageType) => {
 
 const setStorage = (storageType, storage) => {
   const json = JSON.stringify(storage)
-  window.localStorage.setItem(`__chrome.storage.${storageType}__`, json)
+  const data = writeChromeStorageFile(storageType, json)
 }
 
 const scheduleCallback = (items, callback) => {