Windows and the renderer

Create the main window

Configure a BrowserWindow with a preload script and load the Webpack renderer entry produced by Electron Forge.

10 minute lesson

~~~

Create windows in the main process after Electron is ready. Replace the generated window function in src/index.js:

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

let mainWindow = null

function createWindow() {
  const win = new BrowserWindow({
    width: 960,
    height: 700,
    minWidth: 720,
    minHeight: 500,
    show: false,
    webPreferences: {
      preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY,
      contextIsolation: true,
      nodeIntegration: false,
      sandbox: true
    }
  })

  mainWindow = win
  win.on('closed', () => {
    if (mainWindow === win) mainWindow = null
  })

  win.once('ready-to-show', () => win.show())
  win.loadURL(MAIN_WINDOW_WEBPACK_ENTRY)

  return win
}

The two uppercase entry variables are supplied by the Forge Webpack plugin. One points to the renderer page and one points to the bundled preload script.

show: false avoids displaying a partially rendered window. ready-to-show displays it after the first useful paint. For an interface that renders slowly, a matching backgroundColor can be a better choice than delaying the whole window.

The security options are modern defaults, but keep them explicit:

  • nodeIntegration: false keeps Node.js out of page code
  • contextIsolation: true separates preload and page globals
  • sandbox: true restricts the renderer process

Do not solve a preload import error by disabling one of these settings. A sandboxed preload has a limited environment, so move privileged Node.js work into the main process and expose one IPC method.

Open DevTools and verify require is not available to the page. The window should still load because the renderer bundle contains browser-compatible code.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →