Open In App

How to switch between multiple windows of Electron JS application ?

If you have prior knowledge of Web Application Development and thinking to jump into the building of Desktop Application, you are at the right place to start with.  

ElectronJS is an open-source framework that helps to develop a cross-platform desktop application using simple HTML, CSS, and JavaScript. Even if you want to develop an application using Angular or React and trying to build the desktop version of it, Electron JS provides you the same support. Electron uses a headless Chromium browser which provides access to Node JS APIs through Electron’s own APIs.



In any web application, while we click on some links, sometimes a new tab in the browser opens with new content. Also, we think that you observe the same behavior in the case of Desktop Application. When we click on some button in any Desktop Application, it opens a new window on top of the previous window, and until we close the top window (or the new window), the main window won’t work. Electron provides this functionality of opening multiple windows based on button click or click on any link. 

For understanding, let’s say you develop one application, and you want to open the Settings page in another window. And this tutorial will demonstrate how to open the Settings page in a new window using Electron JS. 



We assume that you are familiar with the basic setup of the Electron Application (If not, please go through Create Basic Electron Application). Node and npm need to be installed in your system to run the Electron application. 

Project Structure: Let’s begin with the basic structure of the project as follows.

Project Structure

package.json

{
  "name": "electron-app",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "start": "electron ."
  },
  "author": "Sandip",
  "license": "ISC",
  "dependencies": {
    "electron": "^12.0.2"
  }
}

Copy the main script file (main.js) from Create Basic Electron Application to our app.js which acts as the main process of our application.

 

Write simple HTML code in index.html (As if it is your first window or main window) as follows 




<!DOCTYPE html>
<html>
    <head>
        <title>First Window</title>
    </head>
    <body>
        <div>
            <h1 style="color: green;">
              Hello : This is first window
            </h1>
            <br />
  
            <button onclick="goToSettingsWindow()">
              Go to Settings Window
            </button>
        </div>
    </body>
</html>

Output: 

Initial Window

 

 

app.js: We intend to open a new Settings window while you click on the “Go to Settings Window” button. Let’s check the necessary changes to be done in the app.js file.




const { app, BrowserWindow, ipcMain } = require("electron");
const path = require("path");
  
let mainWindow;
  
// Function to create independent window or main window
function createWindow() {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    // Make sure to add webPreferences with
    // nodeIntegration and contextIsolation
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
    },
    show: false,
  });
  
  // Main window loads index.html file
  mainWindow.loadFile("index.html");
  
  // To maximize the window
  mainWindow.maximize();
  mainWindow.show();
}
  
// Function to create child window of parent one
function createChildWindow() {
  childWindow = new BrowserWindow({
    width: 1000,
    height: 700,
    modal: true,
    show: false,
    parent: mainWindow, // Make sure to add parent window here
  
    // Make sure to add webPreferences with below configuration
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      enableRemoteModule: true,
    },
  });
  
  // Child window loads settings.html file
  childWindow.loadFile("settings.html");
  
  childWindow.once("ready-to-show", () => {
    childWindow.show();
  });
}
  
ipcMain.on("openChildWindow", (event, arg) => {
  createChildWindow();
});
  
app.whenReady().then(() => {
  createWindow();
  
  app.on("activate", () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow();
    }
  });
});
  
app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
  }
});

 

Let’s add the below script  in index.html




const ipc = window.require('electron').ipcRenderer;
  
// Function that will be called on click 
// event of "Go to settings window" button
function goToSettingsWindow(){
  
    // Make sure to do ipc.send('some String'), 
    // where 'some String' must be same with 
    // the first parameter of ipcMain.on() in app.js 
    ipc.send('openChildWindow');  
}

Here we are using ipcRenderer of electron module to send an event ‘openChildWindow‘ and ipcMain (specified in app.js) is  listening this event and call createChildWindow() method.

Let’s create a settings.html file that will be shown in the child window on the button click (‘Go to Settings Window’ button) in the main window.




<!DOCTYPE html>
<html>
<head>
    <title>Settings</title>
</head>
<body>
    <div>
        <h1 style="color: green;">
          Hello : This is Settings window
        </h1>
        <button onclick="goToFirstWindow()">
          Go to Main Window
        </button>
    </div>
</body>
</html>

Output: Before adding “Go to Main Window” functionality, let’s check the output of opening the settings window

 

Let’s add the below script in settings.html to close the settings window and come back to the main window (If you close the window by clicking Window close (the X button in the top-right corner), it is also possible, but sometimes we need to do some other action to be performed before closing the window, like Database update or config update and for that, you need to close the window on button click)




const remote = window.require("electron").remote;
  
function goToFirstWindow() {
  //code for some other action to be performed
  
  //Code to close the window after doing other actions
  remote.getCurrentWindow().close();
}

Here we are accessing remote object of electron module to get currentWindow object.

Output: Let’s check our final application.


Article Tags :