Categories
Programming

Electron open file explorer with file selected43 sec read

After creating a file and writing it to the disk, its nice to show the user the location of the newly created file in the system file explorer.

At the time of writing this there is no option in electron for opening the system file explorer with a file selected. So, like every programmer does I put the title of this post into the google search bar and found this

https://discuss.atom.io/t/opening-the-oss-file-explorer/24348

So this is what I did

function open_file_exp(fpath) {
  var command = '';
  switch (process.platform) {
    case 'darwin':
      command = 'open -R ' + fpath;
      break;
    case 'win32':
      if (process.env.SystemRoot) {
        command = path.join(process.env.SystemRoot, 'explorer.exe');
      } else {
        command = 'explorer.exe';
      }
      command += ' /select,' + fpath;
      break;
    default:
      fpath = path.dirname(fpath)
      command = 'xdg-open ' + fpath;
  }
  console.log(command);
  child_process.exec(command, function(stdout) {
    //Do something if you really need to
  });
}

 

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.

Categories
Programming

An HTML5 desktop app with electron4 min read

Electron let’s you build cross platform desktop apps using HTML5 and javascript. Let’s make a  demo desktop app with electron.

If you haven’t  heard of electron from GitHub, you should go through this Build cross platform desktop apps with JavaScript, HTML, and CSS before continuing.

Without wasting our time let’s get started with the app.

Prerequisites

The app

We shall call our app Dapp – Demo App.

Let’s also create a project folder named dapp and open command window inside the folder.

All the commands have to be run inside this folder.

The first command would be

npm init

Input the required information and our package.json file would be created.

Now we have to install electron which is available as an npm package.

npm install electron-prebuilt --save-dev

We are installing it as developer dependency.

The package.json file has to be modified to run electron at start

{
    "name": "dapp",
    "version": "1.0.0",
    "description": "A demo app made with electron.",
    "main": "index.js",
    "scripts": {
        "start": "electron ."
    },
    "keywords": [
        "electron",
        "demo"
    ],
    "build": {
        "appId": "in.jijnasu.dapp"
    },
    "author": "Hrishikesh M K <hrishikesh.mk1@gmail.com> (https://jijnasu.in)",
    "license": "ISC",
    "devDependencies": {
        "electron-prebuilt": "^1.4.10"
    }
}

Add a start script as shown above.

We have to create a file called index.js, as we have provided it in the package file with the key main.

Let’s just copy the index.js file provided in the electron website.

const {app, BrowserWindow} = require('electron')
const path = require('path')
const url = require('url')

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win

function createWindow () {
  // Create the browser window.
  win = new BrowserWindow({width: 800, height: 600})

  // and load the index.html of the app.
  win.loadURL(url.format({
    pathname: path.join(__dirname, 'index.html'),
    protocol: 'file:',
    slashes: true
  }))

  // Open the DevTools.
  win.webContents.openDevTools()

  // Emitted when the window is closed.
  win.on('closed', () => {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    win = null
  })
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (win === null) {
    createWindow()
  }
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.

The index.js file would load an HTML file called index.html in our main window.

So let’s create one and save it in the same directory.

<!doctype html>
<html>

<head>
    <title>Dapp</title>
    <style>
        html,
        body {
            width: 100%;
            height: 100%;
            position: relative;
            margin: 0;
            padding: 0;
            font-family: Avant Garde, Avantgarde, Century Gothic, CenturyGothic, AppleGothic, sans-serif;
            background-color: #2c3e50;
            color: #ffffff;
        }
        
        #cont {
            text-align: center;
            font-size: 30px;
            height: 300px;
            position: absolute;
            width: 300px;
            left: 50%;
            top: 50%;
            margin-left: -150px;
            margin-top: -150px;
            border: dashed;
        }
    </style>
</head>

<body>
    <div id="cont">
        <h1>Dapp</h1>
        <p id="time">...</p>
        <p id="date">...</p>
    </div>
    <script>
        var time_elem = document.getElementById('time');
        var date_elem = document.getElementById('date');
        window.setInterval(function() {
            var date = new Date();
            date_elem.innerHTML = date.toDateString();
            time_elem.innerHTML = make_valid(date.getHours()) + ':' + make_valid(date.getMinutes()) + ':' + make_valid(date.getSeconds());
        }, 200);

        function make_valid(num) {
            num = parseInt(num);
            if (num < 10) {
                return '0' + num;
            }
            return num;
        }
    </script>
</body>

</html>

Now our app is ready to run. Try it out with this command

npm start

Please note that the command window should be open inside the project folder throughout this tutorial.

Now that our app is ready, the only thing left is to package it.

Packaging electron applications

For packaging we use electron-builder.

First install electron-builder through npm.

npm install electron-builder --save-dev

The documentation for electron-builder tells us to modify the package.json file to add the pack and dist scripts.

A unique app id is also required for the build.

So let’s the modify the file.

{
    "name": "dapp",
    "version": "1.0.0",
    "description": "A demo app made with electron.",
    "main": "index.js",
    "scripts": {
        "start": "electron .",
        "pack": "build --dir",
        "dist": "build",
        "postinstall": "install-app-deps"
    },
    "keywords": [
        "electron",
        "demo"
    ],
    "build": {
        "appId": "in.jijnasu.dapp"
    },
    "author": "Hrishikesh M K <hrishikesh.mk1@gmail.com> (https://jijnasu.in)",
    "license": "ISC",
    "devDependencies": {
        "electron-builder": "^10.4.1",
        "electron-prebuilt": "^1.4.10"
    }
}

And finally run

npm run dist

Comment below if something went wrong.

✌️