Show Open Dialog in Electron

in #utopian-io6 years ago (edited)

electronn.png

https://github.com/electron/electron
The source code for this project can be found
my github profile link

What I will learn?

  • You will learn Open Dialog
  • You will learn how to use the dialog module
  • You will learn how to read the data in the file using the file system
  • You will learn how to send the file using IPC modules

Requirements

Difficulty

  • Intermediate

Description

It’s very important that any application is user friendly
Although electron is a desktop application, it is encoded using html which allows us to create a user friendly application but some parts of javascript may not be user friendly for example alert calls.
As a result we can not create dialog boxes using alert calls
Provides a good interface to fulfill the task of creating electron communication boxes
Let us have aa look at it
Offers a Communication module that we can use to display local dialog boxes to open and save electron files
Develop a sample application for better conceptualization
When I open the application I select a text file and print the data in this text file with index.html
We will take advantage of the file system IPC modules and dialog modüle to create this example
Place a button on the index.html page

<button onclick="clickButton()">Open File</button>

res1.jpg

When this button is clicked open dialog will be opened
Since the dialog modules work in the main process we need to send the information that was clicked to the main process
Define the ipcRenderer modüle so the ipcRenderer will do the sending to the main process

<script>
const {ipcRenderer}=require('electron')

res2.jpg

Let define a function

function clickButton(){
ipcRenderer.send('click-button','true')
}

res2.jpg

The message we send as true will inform you that the main process button click action is true
We should catch this message in the main process and open dialog window
First wedefine the ipcMain module

const {ipcMain}=require('electron')

res3.jpg

I need to send the message that the dialog window opened to the client, so let’s create a method that receives the message

ipcMain.on('openFile',(event,arg)=>{

res4.jpg

I can now define the file system and dialog modules

const {dialog}=require('electron') 
const fs=require('fs')

res5.jpg

We can catch the button clicked message and open the dialog window

ipcMain.onrclick-button',(event,arg)=>{
if(arg=='true'){
dialog.showOpenDialog(function(fileNames){

res6.jpg

We open the window with show Open Dialog method
We can capture the selected file in the window with the function written in it
fileNames is an array that contains all the selected
let’s check that the file is selected

if(fileNames==undefined){
console.log("No file selected");
}
else {
readFile(fileNames[0])
}

res7.jpg
Also read the file with a method
I sent the first element in the method
Now create a method to read the file this method will also send the data to the client in the file

function readFile(filepath){

res8.jpg

We can read the file using the file system

fs.readFile(filepath,'utf-8',(err,data)=>{

res9.jpg

Err stand for error, data represents the data in the file
Let’s check the error

if(err){
alert("An error :"+err.message) 
return
}

resa.jpg

Send this data to the client

event.sender.send('fileData',data)

resb.jpg

So we sent the data to the index.html page, now we get this data

ipcRenderer.sendropenFiler,()=>{
})
ipcRenderer.oncfileData',(event,data)=>{
document.write(data)
})
</script>

resc.jpg

The button is waitng for us to open the dialog window when the application is opened
When we click on button Windows opens
İf you cancel the operation without selecting any file, no file selected message appears
İf you select a text file the text inside the file is printed on my client page
I showed you how to open the dialog window on this tutorial
electron logo source link

Main.js

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

let win

function createWindow() {
   win = new BrowserWindow({width: 800, height: 600})
   win.loadURL(url.format ({
      pathname: path.join(__dirname, 'index.html'),
      protocol: 'file:',
      slashes: true
   }))
}

ipcMain.on('openFile',(event,arg)=>{
  const {dialog}=require('electron')
  const fs=require('fs')

  ipcMain.on('click-button',(event,arg)=>{
    if(arg=='true'){
      dialog.showOpenDialog(function(fileNames){
        if(fileNames==undefined){
          console.log("No file selected");
        }
        else {
          readFile(fileNames[0])
        }
      })
    }
  })

function readFile(filepath){
  fs.readFile(filepath,'utf-8',(err,data)=>{
    if(err){
      alert("An error :"+err.message)
      return
    }
    event.sender.send('fileData',data)
  })
}

})



app.on('ready', createWindow)


Index.html

<!DOCTYPE html>
<html>
   <head>
      <meta charset = "UTF-8">
      <title></title>
   </head>

<script>
const {ipcRenderer}=require('electron')
function clickButton(){
  ipcRenderer.send('click-button','true')
}
ipcRenderer.send('openFile',()=>{
})
ipcRenderer.on('fileData',(event,data)=>{
  document.write(data)
})
</script>


   <body>
    <button onclick="clickButton()">Open File</button>
   </body>
</html>

Package.json

{
  "name": "showDialog",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

Video Tutorial

Sort:  

Thank you for your contribution.

You video structure is effective. I believe you are improving your speech. You can still work on making your English more understandable. I suggest practicing your English with a native English speaker.

There are many many errors in the text of your post. These errors are easy to fix and should not be in a Utopian post. Be sure to be more careful with your text in future contributions. I suggest asking someone to proof read your work for you.

Your contribution has been evaluated according to Utopian rules and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post,Click here


Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]

thank your advice and comment , you are my idol in steemit and utopian
I work hard to improve myself
I am very grateful to you for everything

Hey @sanalrakam
Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Contributing on Utopian
Learn how to contribute on our website or by watching this tutorial on Youtube.

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

Coin Marketplace

STEEM 0.27
TRX 0.13
JST 0.032
BTC 64161.84
ETH 2950.76
USDT 1.00
SBD 3.60