Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Debugging

An Electron app has two kinds of code, and they are debugged differently. The page is debugged with Chromium's developer tools (DevTools), like a website. The main process is debugged like a Node.js program: with terminal output and a debugger attached through the --inspect flag.

DevTools for the page

Electron's default menu has View → Toggle Developer Tools, also Ctrl+Shift+I (Cmd+Option+I on a Mac). With a custom menu, DevTools can be opened from code:

// main.js
win.loadFile('index.html');
 
if (!app.isPackaged) {
  win.webContents.openDevTools();
}

app.isPackaged is false when running with npm start and true in a built app. So DevTools open only during development. The console, breakpoints, Elements and Network all work there.

Main process output

console.log in main.js writes to the terminal the app was started from:

// main.js
ipcMain.handle('notes:save', async (event, notes) => {
  console.log('Saving notes:', notes.length);
  await saveNotes(notes);
});

Every save prints a line with the number of notes to the terminal. Unhandled errors of the main process also appear there.

A debugger for the main process

To set breakpoints in main.js, start Electron with the --inspect flag. Add a script to package.json:

{
  "scripts": {
    "start": "electron .",
    "debug": "electron --inspect=5858 ."
  }
}

Run npm run debug, open chrome://inspect in Chrome and click inspect under Remote Target — DevTools for the main process open.

Debugging in VS Code

VS Code can start Electron itself. Create .vscode/launch.json:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Electron: main",
      "type": "node",
      "request": "launch",
      "cwd": "${workspaceFolder}",
      "runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron",
      "windows": {
        "runtimeExecutable": "${workspaceFolder}/node_modules/.bin/electron.cmd"
      },
      "args": ["."]
    }
  ]
}

Press F5 — the app starts, and breakpoints in main.js stop right in the editor.

A crashed page

If the renderer process crashes, the window turns white and the main process gets an event:

// main.js
win.webContents.on('render-process-gone', (event, details) => {
  console.log('Page crashed:', details.reason);
});

details.reason explains why, for example 'crashed' or 'oom' (out of memory). The window can then be reloaded with win.reload().

Common mistake

Beginners look for console.log output from main.js in the window's DevTools and do not find it. DevTools show only the renderer process and preload. Look for main process messages in the terminal where you ran npm start.

Thanks for reading!

Donate to the site — we work hard for you.