Electron API Quick Reference and Configuration Templates
Main Process API Quick Reference
| module | Description | // 2022-01-01 00:00:00 GMT | Description |
|---|---|---|---|
| app | Control the application lifecycle | app.on('ready'), app.quit(), app.getPath('userData') |
Manage app startup, exit, paths, protocol registration, etc. |
| BrowserWindow | Create and manage windows | new BrowserWindow(options), win.loadFile(), win.loadURL(), win.webContents |
The main UI container of an Electron app, running the renderer process inside |
| ipcMain | Main process communication interface | ipcMain.on(channel, callback), ipcMain.handle(channel, handler) |
Listen for messages or invocation requests from the renderer process |
| Menu | Create application menus | Menu.buildFromTemplate(menuTemplate), Menu.setApplicationMenu(menu) |
Customizable menu items, shortcuts, context menus |
| Tray | System tray management | new Tray(icon), tray.setToolTip(), tray.setContextMenu(menu) |
Show an icon in the taskbar, often used for background-resident apps |
| Dialog | Native system dialogs | dialog.showOpenDialog(), dialog.showSaveDialog(), dialog.showMessageBox() |
System interactions such as file selection, saving, message prompts |
| Notification | System notifications | new Notification({ title, body }).show() |
Send native system notifications, with optional click callbacks |
| Shell | Invoke external system resources | shell.openExternal(url), shell.showItemInFolder(path) |
Open external web pages, folders, executable files |
| Protocol | Register a custom protocol | protocol.registerFileProtocol(), protocol.handle() |
Used for custom resource loading or deep linking |
| Session | Manage sessions, cache, cookies | session.defaultSession.cookies.get(), clearCache() |
Low-level control over browsing data and requests |
| Net | Native HTTP/HTTPS network requests | net.request(options) |
A lower-level network module, with better performance than fetch |
| PowerMonitor | Monitor system power status | powerMonitor.on('suspend'), on('resume') |
Listen for computer sleep, wake, lock-screen and other states |
| Clipboard | Clipboard operations | clipboard.readText(), clipboard.writeText() |
Support cross-platform copy and paste of text, images, etc. |
| GlobalShortcut | Register global shortcuts | globalShortcut.register('CommandOrControl+X', fn) |
Shortcuts that work across windows and in the background |
Renderer Process API Quick Reference
| module | Description | // 2022-01-01 00:00:00 GMT | Description |
|---|---|---|---|
| ipcRenderer | Communicate with the main process | ipcRenderer.send(), ipcRenderer.invoke(), ipcRenderer.on() |
For the renderer process to send, receive and invoke main-process events |
| webFrame | Control the current page content | webFrame.setZoomFactor(), webFrame.insertCSS() |
Dynamically modify page zoom and styles |
| contextBridge | Safely expose APIs | contextBridge.exposeInMainWorld('api', {...}) |
When contextIsolation Interact with the main process safely |
| desktopCapturer | Capture screen content | desktopCapturer.getSources({ types: ['window', 'screen'] }) |
Used for screenshots or screen recording |
| Notification | Notification API | new Notification('标题', { body: '内容' }) |
Send notifications using the browser-standard Notification |
| Clipboard | Clipboard operations | navigator.clipboard.readText() |
Can access the system clipboard (with some features restricted) |
| Web Storage / IndexedDB | Local storage | localStorage.setItem(), indexedDB.open() |
Store lightweight or structured data |
| Fetch / Axios | Network requests | fetch(url), axios.get() |
Used to access remote APIs and load resources |
| DOM / Window | Page control | document.querySelector(), window.open() |
All Web APIs are available |
Common Helper Module Quick Reference
| module | Main Function | Example |
|---|---|---|
| fs | File operations | fs.readFileSync(path), fs.writeFile(path, data) |
| path | Path joining | path.join(__dirname, 'index.html') |
| os | System information | os.platform(), os.homedir() |
| child_process | Execute child processes | exec('ls', callback) |
| electron-store | Persistent configuration | store.set('key', value), store.get('key') |
| sqlite3 / better-sqlite3 | Local database | db.prepare('SELECT * FROM notes').all() |
| axios / node-fetch | Network requests | axios.post(url, data) |
| node-gyp | Native module compilation | node-gyp rebuild |
Configuration File Templates and Notes
package.json Template and Notes
{
"name": "my-electron-app",
"version": "1.0.0",
"description": "示例 Electron 应用",
"main": "main.js",
"scripts": {
"start": "electron .",
"pack": "electron-builder --dir",
"dist": "electron-builder"
},
"devDependencies": {
"electron": "^33.0.0",
"electron-builder": "^24.6.0"
},
"build": {
"appId": "com.example.myelectronapp",
"productName": "MyElectronApp",
"directories": {
"output": "dist"
},
"files": [
"main.js",
"preload.js",
"renderer/**/*"
],
"win": {
"target": "nsis",
"icon": "assets/icon.ico"
},
"mac": {
"category": "public.app-category.productivity",
"icon": "assets/icon.icns"
},
"linux": {
"target": "AppImage",
"icon": "assets/"
}
}
}
Explanation:
| Field | Meaning |
|---|---|
| name / version / description | Application name, version number and description |
| main | Main process entry file (required) |
| scripts | Define command scripts,npm start start,npm run dist package |
| devDependencies | Dev dependencies (Electron, packaging tools, etc.) |
| build | electron-builder configuration items of |
| appId | Unique app ID, used for signing and update identification |
| productName | Application name shown after packaging |
| directories.output | Packaging output path |
| files | Specify the files and directories to package into the application |
| win/mac/linux | Per-platform packaging configuration (icon, target format) |
electron-builder.yml template and description
appId: com.example.myelectronapp
productName: MyElectronApp
directories:
output: dist
files:
- "main.js"
- "preload.js"
- "renderer/**/*"
win:
target: nsis
icon: assets/icon.ico
mac:
target: dmg
icon: assets/icon.icns
linux:
target: AppImage
icon: assets/
publish:
provider: github
repo: my-electron-app
owner: username
Explanation:
| Configuration Item | Description |
|---|---|
| appId / productName | Application unique identifier and name |
| directories.output | Packaging output directory |
| files | List of files to package (wildcards supported) |
| win / mac / linux | Build targets and icon configuration for different systems |
| publish | Publish source configuration for automatic updates (e.g., GitHub Releases) |
TypeScript tsconfig.json template and description
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"strict": true,
"outDir": "./dist",
"rootDir": "./src",
"esModuleInterop": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"skipLibCheck": true
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
Explanation:
| Option | Meaning |
|---|---|
| target | Target JavaScript version for compilation |
| module | Module system, generally used by the Electron main process commonjs |
| outDir / rootDir | Output and source directories |
| strict | Enable strict type checking |
| esModuleInterop | Allow default imports from non-ES modules |
| resolveJsonModule | Support importing JSON files |
| skipLibCheck | Skip declaration file checking to speed up compilation |