Getting Started with Electron: Building Desktop Apps for Web Developers

Advanced IPC Techniques (e.g., Context Isolation)

Section 8

Chapter 4: Inter-Process Communication: Bridging the Gap

Getting Started with Electron: Building Desktop Apps for Web DevelopersChapter 4: Inter-Process Communication: Bridging the Gap

As you delve deeper into Electron development, you'll encounter situations where simple ipcRenderer.send and ipcMain.on become insufficient or introduce potential security risks. This section explores advanced Inter-Process Communication (IPC) techniques that offer more robust and secure ways for your main and renderer processes to interact.

One of the most critical advanced IPC features is Context Isolation. By default, renderer processes have direct access to Node.js APIs, which can be a security vulnerability if untrusted code is loaded into your renderer process. Context isolation creates a separate JavaScript context for your preload script, preventing direct access to Node.js APIs from your renderer code and allowing you to selectively expose only the necessary functionalities.

To enable context isolation, you set the contextIsolation option to true in your webPreferences when creating a BrowserWindow.

const mainWindow = new BrowserWindow({
  webPreferences: {
    preload: path.join(__dirname, 'preload.js'),
    contextIsolation: true,
    nodeIntegration: false,
  }
});

When contextIsolation is true, the preload.js script runs in a privileged context, allowing it to access Node.js APIs. Your main process can then expose specific APIs to the renderer process through the contextBridge module. This acts as a secure gateway, defining what the renderer can and cannot do.

// preload.js
const { contextBridge, ipcRenderer } = require('electron');

contextBridge.exposeInMainWorld('electronAPI', {
  sendMessage: (message) => ipcRenderer.send('message', message),
  onUpdateCounter: (callback) => ipcRenderer.on('update-counter', callback)
});

In your renderer process (e.g., renderer.js), you can then access these exposed APIs. Notice that you can't directly call Node.js functions here, but rather interact with the electronAPI object provided by the preload script.

// renderer.js
window.electronAPI.sendMessage('Hello from renderer!');

window.electronAPI.onUpdateCounter((event, value) => {
  console.log('Counter updated:', value);
});
チャプターへ戻る