Progress Bars in ElectronJS | Set – 2

This article is a continuation of the article: Progress Bars in ElectronJS | Set – 1. In the previous article, we have discussed how to create progress bars in the taskbar/dock icon of the Electron application using the Instance method of the BrowserWindow object. In this article, we will implement a Custom Progress Bar within the Electron Application using the electron-progressbar npm package that we had installed earlier during application setup. We will continue using the same code base from where we left off in the previous article. The project structure and the package.json file also remain the same. As discussed in the previous article, the electron-progressbar package provides an easy and highly customizable API to display and control progress bars within the Electron application. This package can only be imported and used directly in the Main Process. To import and use this package in the Renderer Process, we need to perform an additional change to the main.js file. We cannot use the Electron remote module in this case since it is an external package. Also, this package can only be used after the ready event of the app Module is emitted in the Main Process of the application.

  • main.js: Add the following snippet in that file.  After that, we can import and use this package in the Renderer Processes of the application since we have added that import to the global object in the main.js file. In case, we import the electron-progressbar package directly in the Renderer Process, we will encounter the Error: Uncaught TypeError: BrowserWindow is not a constructor. This Error is thrown because internally this package tries to initialize a BrowserWindow object directly from Electron without using the remote module which is only supported in the Main Process and not in the Renderer Processes.

javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

const { app, BrowserWindow } = require('electron')
global.ProgressBar = require('electron-progressbar');

chevron_right


  • index.html: Add the following snippet in that file.

html

filter_none

edit
close

play_arrow

link
brightness_4
code

<h3>Progress Bar in Electron</h3>
    <button id="progress">
        Click to Launch BrowserWindow Progress Bar
    </button>
    <br><br>
    <button id="custom">
        Click to Launch Electron ProgressBar from Package
    </button>

chevron_right


  • index.js: The Click to Launch Electron ProgressBar from Package button does not have any functionality associated with it yet. To change this, add the following code in the index.js file.

javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

const { getGlobal, app, BrowserWindow } = electron.remote
// Importing ProgressBar in the Renderer Process from global
// Actual Import in main.js file
const ProgressBar = getGlobal('ProgressBar');
 
// Cannot Import Directly in the Renderer Process
// const ProgressBar = require('electron-progressbar')
 
var custom = document.getElementById('custom');
custom.addEventListener('click', () => {
    var progressBar = new ProgressBar({
        abortOnError: false,
        // Determinate Progress Bar
        indeterminate: false,
        initialValue: 0,
        maxValue: 100,
        // On Completion, Progress Bar window will not close.
        closeOnComplete: false,
        title: 'Title of the Progress Bar',
        text: 'Text of the Progress Bar',
        detail: 'Detail to Show actual Progress, ' +
                'Can be set as Dynamic to show actual Status',
        style: {
            text: {},
            detail: {},
            bar: { 'width': '100%', 'background-color': '#BBE0F1' },
            value: {}
        },
        browserWindow: {
            parent: null,
            modal: true,
            resizable: false,
            closable: false,
            minimizable: false,
            maximizable: false,
            width: 500,
            height: 170,
            // Important - If not passed, Progress Bar will not be displayed.
            webPreferences: {
                nodeIntegration: true
            }
        }
    });
 
    progressBar
        .on('completed', (value) => {
            console.log(progressBar.isCompleted());
            console.log('Progress Bar Completed');
            progressBar.detail = 'Task completed. Exiting...';
        })
        .on('ready', () => {
            console.log(progressBar.getOptions())
        })
        .on('aborted', (value) => {
            console.log(`aborted... ${value}`);
        })
        .on('progress', (value) => {
            progressBar.detail =
            `Value ${value} out of ${progressBar.getOptions().maxValue}...`;
        });
 
    setInterval(function () {
        if (!progressBar.isCompleted()) {
            progressBar.value += 1;
        }
    }, 100);
});

chevron_right


The new ProgressBar(options) Constructor is used to create and initialize a new progress bar within the application. We need pass in an options object to this constructor for initializing the progress bar with custom configurations. It takes in the following parameters. This Constructor returns an Instance of the ProgressBar



  • abortOnError: Boolean This parameter defines whether the progress bar should abort and close if an Error occurs internally. The default value is false.
  • indeterminate: Boolean This parameter defines and initializes the mode of the progress bar. If set to true, an indefinite progress bar is initialized which is equivalent to the indeterminate mode as discussed in the previous article. If set to false, the progress bar will be initialized in determinate mode. The default value is true. In this tutorial, we have initialized a determinate progress bar and used the setInterval() method to simulate an actual progress bar task. Refer to the output for a better understanding.
  • initialValue: Integer This parameter sets the initial value of the progress bar. This can only be used for a determinate progress bar i.e. when indeterminate: false. The default value is 0.
  • maxValue: Integer This parameter sets the maximum value of the progress bar. When the progress bar value becomes equal to this parameter value, the progress bar will be set as completed and the complete event will be fired. The isCompleted() Instance method will return true. This can only be used for a determinate progress bar i.e. when indeterminate: false. The default value is 100.
  • closeOnComplete: Boolean This parameter defines whether the progress bar window should be closed automatically on completion. If set to false, the progress bar must be manually closed by calling the close() Instance method or closing the progress bar window task. The default value is true.
  • title: String This parameter defines the Text to be shown on the title bar of the progress bar window. The default value is Wait
  • text: String This parameter defines the Text to be shown inside the window but above the progress bar element. The default value is Wait… This value can be dynamically set or changed using the Instance Properties of the progress bar.
  • detail: String This parameter defines the Text to be shown between the text parameter and the actual progress bar element. This parameter is used to display the current status of the progress bar i.e. the value completed or the progress percentage of the actual task being done. This parameter does not have any default value. This value can be dynamically set or changed using the Instance Properties of the progress bar.
  • style: Object (Optional) This parameter takes in an object. This is where we define the visual styles for the different elements of the progress bar according to our own CSS styles. It takes in the following parameters. All Styles defined follow strict CSS Rules.
    • text: Object This parameter takes in an object containing any CSS properties for styling the text element of the progress bar. This parameter does not have any default object.
    • detail: Object This parameter takes in an object containing any CSS properties for styling the detail element of the progress bar. This parameter does not have any default object.
    • bar: Object This parameter takes in an object containing any CSS properties for styling the bar element of the progress bar. This parameter has a default CSS object predefined: {‘width’:’100%’, ‘background-color’:’#BBE0F1′} for the bar element.
    • value: Object This parameter takes in an object containing any CSS properties for styling the value element in the progress bar window. This parameter has a default CSS object predefined: {‘background-color’:’#0976A9′} for the value element.
  • browserWindow: Object This parameter takes in the Electron’s BrowserWindow Instance options. Although only a few properties are used as per default, we can specify any number of properties for the BrowserWindow Instance options object which are supported. This parameter defines the characteristics of the progress bar window. It takes in the following parameters. 
    Note: It is mandatory to pass this object with the default parameters required for the progress bar to behave correctly. A detailed list of all the default parameters required for this object is given below.
    • parent: Instance of BrowserWindow This parameter takes in a BrowserWindow instance. If passed, the progress bar window will always show on top of the parent window and will block it so that the users can’t interact with it until the progress bar is completed/aborted and closed. Default value passed is null. When the Instance of the BrowserWindow object is passed in this parameter, the parent window is said to be informed.
    • modal: Boolean This parameter defines whether the progress bar window is a modal window or not. A modal window is a child window that disables parent window. This parameter will only work if the progress bar window is a child window i.e. when the Instance of the BrowserWindow object is passed in the parent parameter. A child window is always shown on the top of the parent window. The default value for this parameter is true.
    • resizable: Boolean This parameter defines whether the progress bar window is resizable or not. The default value is false.
    • closable: Boolean This parameter defines whether the progress bar window is closable or not i.e. whether the user can close this progress bar window manually. The default value is false. When this parameter is set to false, the close icon is still shown in the title bar of the progress bar window but it is unresponsive.
    • minimizable: Boolean This parameter defines whether the progress bar window can be minimized or not. The default value is false.
    • maximizable: Boolean This parameter defines whether the progress bar window can be maximized or not. The default value is false.
    • width: Integer This parameter defines the width of the progress bar window in Pixels. The default value for the width of the progress bar window is 450px.
    • height: Integer This parameter defines the height of the progress bar window in Pixels. The default value for the height of the progress bar window is 175px.

The Instance of the ProgressBar returned from the Constructor supports the following Instance Events. The on(eventName, listener) Instance method adds the listener function for the eventName event. No checks are made to see if the listener function has already been added. Multiple calls passing the same combination of eventName event and listener function will result in the listener being added and called multiple times. This Instance method returns a reference to this so that multiple EventListener calls can be chained together to the same ProgressBar Instance. Refer to the code for a better understanding. 

  • ready: Event This Instance Event is fired when the progress bar is initialized and ready to be used. As already mentioned above, the progress bar can only be used after the ready Event of the app module is emitted.
  • progress: Event This Instance Event is fired only in the case of determinate progress bars i.e. when indeterminate: false. This Instance Event is fired every time the value of the progressBar changes. It receives a single parameter named value: Integer which represents the current value of the progress. This Instance event is used to dynamically set and display the current status of the progress bar to the user. Refer to the code for better understanding.
  • completed: Event This Instance Event is fired when the progress bar is completed, i.e. when its value becomes equal to the maxValue parameter defined or the Instance method complete() is called on the progress bar. It receives a single parameter named value: Integer which represents the current value of the progress.
  • aborted: Event This Instance Event is fired when the progress bar is closed but it’s not completed yet i.e. when the user manually closes progress bar window (closable: true) or the Instance method close() is called before the progress bar is completed i.e. before the completed Instance event has fired. It receives a single parameter named value: Integer which represents the current value of the progress at which it was aborted.

The Instance of the ProgressBar returned from the Constructor supports the following Instance Properties. These Instance Properties can be used to dynamically change the status of the progress bar. 

  • value: Integer This Instance Property is used to Get or dynamically Set the Current progress of the progress bar. When this value parameter changes, the progress Instance Event is fired and this parameter is passed to the Instance Event. This Instance Property is only available for determinate progress bars. Refer to the code for better understanding.
  • text: String This Instance Property is used to Get or dynamically Set the text parameter. This represents the Text to be shown inside the progress bar window but above the progress bar element.
  • detail: String This Instance Property is used to Get or dynamically Set the detail parameter. This represents the Text to be shown between the text parameter and the actual progress bar element. This parameter is used to display the current status of the progress bar and can be dynamically changed based on the value parameter. Refer to the code for better understanding.

Additionally, The Instance of the ProgressBar returned from the Constructor supports the following Instance Methods. These Instance methods are useful for controlling the behaviour of the progress bar and to check the current status of the progress bar. 

  • isCompleted(): This Instance method returns a Boolean value which represents the current status of the progress bar. This method will return true only when the progress bar is marked as completed, otherwise, it returns false.
  • setCompleted(): This Instance method marks the status of the progress bar as complete. If the progress bar is indeterminate, a manual call to this Instance method is required because it’s the only way to complete the task and trigger the complete event, otherwise the progress bar would be displayed forever. This method does not have a return type.
  • isInProgress(): This Instance method returns a Boolean value which represents the current status of the progress bar. This method will return true if the progress bar has not been completed or aborted yet, otherwise, it returns false.
  • close(): This Instance method closes the progress bar window. If the progress bar is not completed yet, it’ll be aborted and Instance Event aborted will be fired. This Instance method does not have a return type. If closable: false in the browserWindow parameter, then a call to this method is required to terminate the progress bar window task.
  • getOptions(): This Instance method simply returns an Object representing all the options which were defined and set for the progress bar Constructor at the time of initialization.

At this point, we have successfully implemented a determinate progress bar which is visible in the application window with the help of the electron-progressbar npm package. For this tutorial, we have made the progress bar dynamic by simulating an actual task using the setInterval() method. Upon launching the Electron application, we should see the following Output:
 

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : radheshkhanna