How to switch between multiple windows of Electron JS application ? - GeeksforGeeks

06 Aug, 2021
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
node_modules: This contains the node JS packages which has been created while you do npm init -y
app.js: This the main Electron JS file, where we specify our application window configurations
index.html: This is the main HTML file (Consider it as the main page of our application)
package-lock.json: This file has automatically been generated by npm while we modify something in node_modules or package.json
package.json: This file has been generated by npm and it contains the additional dependencies of our project (like an electron) and some other settings
settings.html: This is the settings HTML file (which will be shown to settings window)
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 
index.html
<!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.
app.js
const { app, BrowserWindow, ipcMain } = require("electron");const path = require("path");  let mainWindow;  // Function to create independent window or main windowfunction 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 onefunction 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();  }});
 
Import ipcMain from electron module
Add createChildWindow() method as above which basically includes all the settings and configuration of child window (i.e. Settings Window)
If you do, childWindow.parent = mainWindow as above, then until child window will be closed, parent window will be disabled.
If you omit childWindow.parent, then a new window will be opened, but there will not be any connection between the child window and the parent window.
Include ipcMain.on(‘openChildWindow’, (event, arg) => { createChildWindow(); } ); basically call createChildWindow() method while we send “openChildWindow” event on button click through ipcRenderer.
Add webPreferences property with all the key-values as mentioned above to mainWindow object which enables us to use Electron’s remote, ipcRenderer for working with child window.
Let’s add the below script  in index.html
Javascript
const ipc = window.require('electron').ipcRenderer;  // Function that will be called on click // event of "Go to settings window" buttonfunction 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.
settings.html
<!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)
Javascript
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.
saurabh1990aror
ElectronJS
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
How to remove duplicate elements from JavaScript Array ?
How to get selected value in dropdown list using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?