Open In App

Custom Messages in ElectronJS

Last Updated : 28 May, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime.

One of the ways how an Electron application interacts with the user is through Message boxes and Alerts. Sometimes during the execution of the application, a condition arises which needs the user’s attention or the code encounters an error and the user needs to be made aware of it. In such cases, the execution flow cannot move forward without user intervention. Electron provides us with a convenient technique by which the user can be made aware of the problem and take necessary action on it. Electron provides us with a built-in dialog module to display Custom Message boxes and Alerts for interacting with the user. This tutorial will use the instance methods of the dialog module to demonstrate Custom Messages in Electron.

We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system.

Custom Messages in Electron: The dialog Module is part of the Main Process. To import and use the dialog Module in the Renderer Process, we will be using Electron remote module.

  • Project Structure:
    Project Structure

Example: Follow the given steps to build Custom Message boxes in Electron.

  • Step 1: Navigate to an Empty Directory to setup the project, and run the following command,
    npm init

    To generate the package.json file. Install Electron using npm if it is not installed.

    npm install electron --save

    This will install the required node_modules dependencies. Copy any Image file of your choosing into the assets folder and name it as image.png. In this tutorial, we will be using the Electron logo as the image.png file.

    package.json:

    {
      "name": "electron-message",
      "version": "1.0.0",
      "description": "Custom Messages in Electron",
      "main": "main.js",
      "scripts": {
        "start": "electron ."
      },
      "keywords": [
        "electron"
      ],
      "author": "Radhesh Khanna",
      "license": "ISC",
      "dependencies": {
        "electron": "^8.2.5"
      }
    }
    
  • Step 2: For the Boilerplate code of the main.js file, Refer this link. We have modified the code to suit our project needs.

    main.js:




    const { app, BrowserWindow } = require('electron')
      
    function createWindow () {
      // Create the browser window.
      const win = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
          nodeIntegration: true
        }
      })
      
      // Load the index.html of the app.
      win.loadFile('src/index.html')
      
      // Open the DevTools.
      win.webContents.openDevTools()
    }
      
    // 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.
    /* The 'dialog.showErrorBox()' method can be used before 
       this event occurs. */ 
    // This method is equivalent to 'app.on('ready', function())'
    app.whenReady().then(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 (BrowserWindow.getAllWindows().length === 0) {
        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.

    
    

  • Step 3: Create the index.html file and index.js file within the src directory. We will also copy the boilerplate code for the index.html file from the above-mentioned link. We have modified the code to suit our project needs.

    index.html:




    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8">
        <title>Hello World!</title>
                               /security#csp-meta-tag -->
        <meta http-equiv="Content-Security-Policy" 
              content="script-src 'self' 'unsafe-inline';" />
      </head>
      <body>
        <h1>Hello World!</h1>
        We are using node 
        <script>
            document.write(process.versions.node)
        </script>, Chrome 
        <script>
            document.write(process.versions.chrome)
        </script>, and Electron 
        <script>
            document.write(process.versions.electron)
        </script>.
      
        <h3>Custom Messages in Electron</h3>
        <button id="show">Show Custom Message Box</button>
      
        <br><br>
        <button id="error">Show Error Message Box</button>
          
        <!-- Adding Individual Renderer Process JS File -->
        <script src="index.js"></script>
      </body>
    </html>

    
    

    Output: At this point, our application is set up and we can launch the application to check the GUI Output. To launch the Electron Application, run the command.

    npm start

  • Step 4: The Show Custom Message Box button does not have any functionality associated with it yet. To change this, add the following code in the index.js file.

    The dialog.showMessageBox(browserWindow, options) is used with all default/basic values for the options Object. Using this Instance method shows the Message box and will block the application execution until the message box is closed successfully with appropriate action from the user. It takes in the following parameters.

    • browserWindow: BrowserWindow (Optional) The BrowserWindow Instance. This argument allows the dialog to attach itself to the parent window, making it a modal. A modal window is a child window that disables the parent window. If BrowserWindow is not shown, dialog will not be attached to it. In such case It will be displayed as independent window. In the above code, the BrowserWindow instance is not being passed to the dialog, therefore the dialog opens as an independent window on clicking the Show Custom Message Box button.
    • options: Object It takes in the following parameters,
      • type: String (Optional) It can hold the following values.
        • none
        • info
        • error
        • question
        • warning

        Each of these values signifify the type of Message Box that you want to display to the user. Default value is none. On Windows, question displays the same icon as info, unless the icon property is explicitly set. On macOS, both warning and error display the same warning icon. Each of these values have a default System OS sound associated with it except for the default value.

      • buttons: String[] (Optional) It represents an Array for the labels of the Buttons that you wish to display on the Custom Message box. An Empty array will result in one button being displayed, labeled OK.
      • defaultId: Integer (Optional) The index of the button in the buttons array which will be selected by default when the Custom Message box is opened. This property is dependent on the noLink property. This is demonstrated in the following Steps.
      • title: String (Optional) The title to be displayed on the Message box. Some OS platforms and their respective versions do not support this property.
      • message: String The main contents of the Message box.
      • detail: String (Optional) Extra Information to be displayed in the Message box below the message property.
      • checkboxLabel: String (Optional) Label of the checkbox. This property automatically includes the checkbox with the given label in the custom Message box.
      • checkboxChecked: Boolean (Optional) This property represents the initial state of the checkbox. The default value of this property is false.
      • icon: NativeImage (Optional) The icon to be displayed on the Message box. If this property is defined, it will override the default system icons for the type property, irrespective of its value. This property takes in a NativeImage instance or the filepath of an image. In this tutorial, we will pass the filepath for the image.png file located in the assets folder using the path module.
      • cancelId: Integer (Optional) The index of the button to be returned when the dialog is cancelled, via the Esc key. By default this is assigned to the first button with Cancel or No as the label in the buttons array property. If no such labeled buttons exist and this option is not set, 0 will be used as the return value. This is demonstrated in the following Steps.
      • noLink: Boolean (Optional) This property is supported on Windows only. When this property is set, Electron will automatically try to figure out which one of the buttons are common button labels e.g. Cancel, Yes, No, OK etc, and show the other button labels as command links in the dialog. This property is used to make the dialog window appear in style with modern Windows OS apps and themes. By default, this property is set to false. In case all common button labels are used, this property will have no effect. This property is demonstrated in the following Steps.
      • normalizeAccessKeys: Boolean (Optional) Normalize the keyboard access keys across platforms. Default value is false. Enabling this property assumes the ‘&’ wildcard is used in the button labels. These labels will be converted so that they work on each platform accordingly. ‘&’ characters are removed altogether on macOS, converted to _ on Linux, and no action is taken on Windows.

    The dialog.showMessageBox(browserWindow, options) returns a Promise. It resolves to an Object containing the following parameters,

    • response: Integer The index of the button clicked as defined in the buttons array property.
    • checkboxChecked: Boolean The checked state of the checkbox if checkboxLabel property was set. By default, will return false.

    index.js:




    const electron = require('electron');
    const path = require('path');
      
    // Importing dialog module using remote
    const dialog = electron.remote.dialog;
      
    var showBox = document.getElementById('show');
      
    showBox.addEventListener('click', (event) => {
        // Resolves to a Promise<Object>
        dialog.showMessageBox({
            // option Object
            type: 'none',
            buttons: [],
            defaultId: 0,
            icon: '',
            title: 'This is the Title',
            message: 'This is a Message',
            detail: 'This is extra Information',
            checkboxLabel: 'Checkbox',
            checkboxChecked: false,
            cancelId: 0,
            noLink: false,
            normalizeAccessKeys: false,
        }).then(box => {
            console.log('Button Clicked Index - ', box.response);
            console.log('Checkbox Checked - ', box.checkboxChecked);
        }).catch(err => {
            console.log(err)
        }); 
    });

    
    

    Output: We should now be able to successfully trigger a basic Custom Message Box on clicking the Show Custom Message Box button.

    Note: If the user tries to continue the execution of the application without successfully closing the Custom Message box, the following message is shown on the console:

    Attempting to call a function in a renderer window that 
    has been closed or released. Function provided here: undefined
  • Step 5: We will now modify the options Object of the Custom Message Box to see the different outputs,
    • type: String Defining the different types of Message boxes.
      • type: ‘info’type: 'info'
      • type: ‘warning’
        type: 'warning'
      • type: ‘error’
        type: 'error'
    • buttons: String[] We will define Custom labels for the buttons array property and see the respective outputs by changing the noLink property.
      • buttons: [‘Cancel’, ‘OK’, ‘Button-1’, ‘Button-2’], noLink: false, defaultId: 0
        noLink: 'false'

        Note: In this case the defaultId property should highlight the Cancel button, but instead the Button-1 label is selected. This is due to the behaviour defined by the noLink property.

      • buttons: [‘Cancel’, ‘OK’, ‘Button-1’, ‘Button-2’], noLink: true, defaultId: 0
        noLink: 'true'

        Note: The Cancel button is selected by default as per expected behaviour.

    • cancelId: Integer Evaluating the behaviour of the cancelId property. This behaviour is invoked by pressing the Esc key on the keyboard.
      • buttons: [‘Cancel’, ‘OK’, ‘Button-1’, ‘Button-2’], cancelId: 100, noLink: true

        Note: The value returned is 100 as set in the cancelId property.

      • buttons: [‘Cancel’, ‘OK’, ‘Button-1’, ‘Button-2’], cancelId: 100, noLink: false

        Note: The value returned is 0 despite setting the cancelId property value to 100.

    • icon: NativeImage We will be passing the filepath of the image.png file located in the assets folder.
      • buttons: [‘Cancel’, ‘OK’, ‘Button-1’, ‘Button-2’], icon: path.join(__dirname, ‘../assets/image.png’), noLink: true
        noLink: 'true'
      • buttons: [‘Cancel’, ‘OK’, ‘Button-1’, ‘Button-2’], icon: path.join(__dirname, ‘../assets/image.png’), noLink: false
        noLink: 'false'

      Note: Using the icon property disables the default system OS sound for the type property, irrespective of its value.

    We can also assign different behaviours to each button in the Message box by simply comparing the index value of the buttons array property with the response parameter returned by Promise.

    index.js:




    .then(box => {
        console.log('Button Clicked Index - ', box.response);
        console.log('Checkbox Checked - ', box.checkboxChecked);
      
        if (box.response === 0) {
            console.log('Cancel Button was clicked');
        } else if (box.response === 2) {
            console.log('Button-1 was clicked');
        }
     }).catch(err => {
        console.log(err)
     }); 

    
    

    Output:

  • Step 6: Electron also provides us with an instance Method specifically designed for Error Messages. In the above code, the Show Error Message Box button does not have any functionality associated with it. To change this add the following code in the index.js file.

    The dialog.showErrorBox(title, info) takes in the following parameters. It does not have any return value. This method is not customizable like the dialog.showMessageBox() method but this method can be safely called before the ready event of the app module is emitted. Refer to the highlighted code in the main.js file. It is usually used to display errors in the application startup stages. If called before the ready event of the app module on Linux, the message will be emitted to stderr, and no GUI dialog will appear.

    • title: String The title of the Error box.
    • info: String The text information to display in the Error box below the title property.

    index.js:




    var error = document.getElementById('error');
      
    error.addEventListener('click', (event) => {
        dialog.showErrorBox('This is the Title', 'This is the Content');
    });

    
    

    Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads