Categories
Programming

Electron: Share sessionStorage between window and webView?1 min read

I wanted to declare global const/var that were specific for an app instance.

Here is a scenario –

  • The app asks for username as soon as it starts and saves it for use unitil the app is closed.
  • If the app was run two times, I didn’t want these instances to have the same username if different usernames were chosen at the start. That is, if I change the username in one instance, didn’t want it to change in the other instance.
  • Also inside the app instance I wanted the saved username to be available in all created webViews and newly created BrowserWindows.

My options

  • localStorage – Naaah, it would be same for all app instances.
  • sessionStorage –  No, it is not shared with webViews and windows created inside the app.
  • global – Yessss, thats it.

How to use it?

Inside the initial script declare this

global.settings = {
    user_name: null
};

(Note- You do not have to use “settings” , you can use whatever you want)

Now in the initial screen, I can do this to change the value

const {
  remote
} = require('electron');

remote.getGlobal('settings').user_name = 'The selected username';

And that’s it.

Leave a Reply

Your email address will not be published. Required fields are marked *