|
| 1 | +--- |
| 2 | +layout: post |
| 3 | +title: "Electron contextIsolation + Preload Security Pattern" |
| 4 | +date: 2025-12-05 09:00:00 +0900 |
| 5 | +categories: [Development, Tips] |
| 6 | +tags: [Electron, security, contextIsolation, preload, IPC] |
| 7 | +author: "Kevin Park" |
| 8 | +lang: en |
| 9 | +excerpt: "Secure your Electron app by using contextIsolation and preload scripts to restrict renderer access to Node.js." |
| 10 | +--- |
| 11 | + |
| 12 | +## Problem |
| 13 | + |
| 14 | +With `nodeIntegration: true`, the renderer (webpage) can directly access the filesystem via `require('fs')`. If loading external URLs, this is a critical security risk. |
| 15 | + |
| 16 | +## Solution |
| 17 | + |
| 18 | +```javascript |
| 19 | +// main.js |
| 20 | +const mainWindow = new BrowserWindow({ |
| 21 | + webPreferences: { |
| 22 | + preload: path.join(__dirname, 'preload.js'), |
| 23 | + contextIsolation: true, // separate renderer and Node.js contexts |
| 24 | + nodeIntegration: false, // block require in renderer |
| 25 | + } |
| 26 | +}); |
| 27 | +``` |
| 28 | + |
| 29 | +```javascript |
| 30 | +// preload.js - bridge between main and renderer |
| 31 | +const { contextBridge, ipcRenderer } = require('electron'); |
| 32 | + |
| 33 | +contextBridge.exposeInMainWorld('electronAPI', { |
| 34 | + scanNetwork: () => ipcRenderer.invoke('scan-network'), |
| 35 | + getVersion: () => ipcRenderer.invoke('get-version'), |
| 36 | + onScanResult: (callback) => |
| 37 | + ipcRenderer.on('scan-result', (_, data) => callback(data)), |
| 38 | +}); |
| 39 | +``` |
| 40 | + |
| 41 | +```javascript |
| 42 | +// renderer.js - use in the webpage |
| 43 | +const results = await window.electronAPI.scanNetwork(); |
| 44 | +``` |
| 45 | + |
| 46 | +## Key Points |
| 47 | + |
| 48 | +- With `contextIsolation: true`, the preload script's globals and the renderer's globals are completely separate. Only functions exposed via `contextBridge.exposeInMainWorld` are accessible. |
| 49 | +- The renderer can only use what's defined in `window.electronAPI`. Dangerous access like `require('child_process')` is impossible. |
| 50 | +- `ipcRenderer.invoke` returns a Promise for bidirectional communication. Handle it in the main process with `ipcMain.handle`. |
0 commit comments