Code Monkey home page Code Monkey logo

electron-browser-storage's Introduction

electron-browser-storage

Access localStorage and sessionStorage from the Electron Main process.

Install

npm install electron-browser-storage

Usage

The methods are promise-based and have the same code signature as the Storage interface methods. The only exception is that .length is implemented as a method .length().

Note: storage methods must be called after the app's ready event.

// In main process
const { localStorage, sessionStorage } = require('electron-browser-storage');

app.on('ready', async () => {
  // Async/await
  await localStorage.setItem('favorite_number', 12);
  await localStorage.getItem('favorite_number'); // '12'
  await localStorage.key(0); // 'favorite_number'
  await localStorage.length(); // 1
  await localStorage.removeItem('favorite_number');
  await localStorage.clear();

  // Promises
  sessionStorage.setItem('favorite_color', 'blue')
    .then(() => sessionStorage.getItem('favorite_color')) // 'blue'
    .then(() => sessionStorage.key(0)) // 'favorite_color'
    .then(() => sessionStorage.length()) // 1
    .then(() => sessionStorage.removeItem('favorite_color'))
    .then(() => sessionStorage.clear());
});

API

Promise-based versions of the Storage interface methods.

Storage.length()

Returns a promise that resolves to the number of items in the storage.

Storage.key(index)

Returns a promise that resolves to the key at the given index.

Storage.getItem(key)

Returns a promise that resolves to the value for the given key.

Storage.setItem(key, value)

Sets the value for the given key and returns a promise that resolves when complete.

Storage.removeItem(key)

Removes the item at the given key and returns a promise that resolves when complete.

Storage.clear()

Removes all keys and values and returns a promise that resolves when complete.

Security Concerns

Under the covers, this uses webContents.executeJavaScript() to access localStorage and sessionStorage in the renderer process.

// This is what the call to setItem() looks like
localStorage.setItem = (key, value) => {
  return win.webContents.executeJavaScript(`window.localStorage.setItem('${key}', '${value}');`);
};

Because nothing is being escaped, be careful when saving user input, since code injection is possible.

// Example of code injection
const userInput = `'); someInjectedCode(); ('`;
await localStorage.setItem('user_name', userInput);

// Resulting in this getting executed
win.webContents.executeJavaScript(`window.localStorage.setItem('user_name', ''); someInjectedCode(); ('');`);

I'm still trying to figure out how to get around this. If you have any ideas, feel free to DM me or open an issue.

electron-browser-storage's People

Contributors

jerry1100 avatar

Stargazers

Firmansyah Yanuar avatar  avatar Kai avatar  avatar SnnSnn avatar Heyong avatar Daniel Maricic avatar  avatar f4n0 avatar Jin Lu avatar Johannes Millan avatar 风之化身 avatar  avatar Daniel Petelin avatar  avatar Anthony avatar Benjamin Høegh avatar Ben Redden avatar  avatar Nguyễn Trường Khôi avatar Junpei Kawamoto avatar

Watchers

James Cloos avatar  avatar  avatar

electron-browser-storage's Issues

Escape string

I don't know but if code injection starts with ') and ends with ') here is a function to check if it's a code injection

function isCodeInjection( value ){
	let regex = /^.*'.*\).*\(.*'.*$/;
	
    return value !== undefined && value.match(regex) != null;
}

this.setItem = (key, value) => !isCodeInjection(value) && execute(window.${storageName}.setItem('${key}', '${value}'););

sessionStorage doesn't work only localStorage

I have a small learning Electron Program under Electron15.0.0 and tried your module.
Everything works fine when I use localStorage but when I change to sessionStorage I don't recover anything on the renderer side.
I tried to put some key, value directly in the console of my BrowserWindow and the sessionStorage works correctly.
Would you have any cue

Setting a value containing backslashes

Should this work with the package (example values are from browser native implementation)?

const key = 'pathSetting';
const path = '\\Users\\Denis';
objIn = { path };
saved = JSON.stringify(objIn);         // ==> '{"path":"\\Users\\Denis"}'
localStorage.setItem(key, saved);      // pathSetting:"{"path":"\\Users\\Denis"}"
loaded = localStorage.getItem(key);    // ==> '{"path":"\\\\Users\\\\Denis"}'
objOut = JSON.parse(loaded)            // ==>  { path: "\\Users\\Denis" }
objIn.path === objOut.path             // ==> true

As I'm sure you're aware, substituting this value into a string of JavaScript source, as you are, loses some backslashes.
Have you tried doubling any backslashes in the value being set?

Using LocalStorage in main.dev.js will not trigger 'window-all-closed' and after app quit, 4 dangling processes will remain

Electron: 7.1.2
electron-browser-storage: 1.0.6

In main.dev.js on app ready, I init my session:

function initSession(){
  // Session Config
  const filter = {
    urls: [constants.webRequestUrlFilter + '*']
  };

  session.defaultSession.webRequest.onBeforeSendHeaders(filter, (details, callback) => {
    details.requestHeaders.Origin = constants.originHeader;

    localStorage.getItem('AUTH:authToken').then(function(authToken){
      if (authToken){
        details.requestHeaders['AUTH-TOKEN'] = authToken;
      }
      callback({
        cancel: false,
        requestHeaders: details.requestHeaders
      });
    });


  });
}

Just the import of LocalStorage const { localStorage } = require('electron-browser-storage'); , will make 4 dangling processes after app quits.

Also window-all-closed is not called whit localStorage is imported

You can make `length` be a property

You can make length be a property

Object.defineProperty(this, "length", {
  get : function(){
    return execute(`window.${storageName}.length;`);
  }
);

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.