Electron Advanced Topics
Electron can not only build cross-platform desktop applications but also supports deep system integration and advanced feature extensions. Mastering these advanced techniques makes apps more professional and powerful.
Native Node Module Integration
Using node-gyp
- node-gyp is a Node.js native module build tool that supports compiling C/C++ modules
-
Installation:
npm install -g node-gyp
- Initialize the project:
node-gyp configure node-gyp build
- Output
.nodefile, which can be loaded directly in Electron:const native = require('./build/Release/native.node')
Compile native modules
- Native modules must be compiled against Electron's Node version and ABI
- Use
electron-rebuildTools:npm install --save-dev electron-rebuild npx electron-rebuild
- Ensure the module is compatible with the current Electron version
Common Problem Solutions
- ABI incompatibility: Electron uses a different Node version, requiring
electron-rebuild - Compilation failure: Check the C++ build environment (Windows requires Visual Studio Build Tools, macOS requires Xcode Command Line Tools)
- Path issues: Ensure the module path is correct, load using an absolute path
.nodefile
Deep system integration
System theme detection
- Detect dark/light theme:
const { nativeTheme } = require('electron') console.log(nativeTheme.shouldUseDarkColors) nativeTheme.on('updated', () => { console.log('主题更新:', nativeTheme.shouldUseDarkColors) }) - Prevent the system from sleeping:
const { powerSaveBlocker } = require('electron') const id = powerSaveBlocker.start('prevent-display-sleep') powerSaveBlocker.stop(id) - Detect power status:
const { systemPreferences } = require('electron') console.log(systemPreferences.getSystemIdleTime())
Screen management
- Get screen information:
const { screen } = require('electron') const primaryDisplay = screen.getPrimaryDisplay() console.log(primaryDisplay.size) - Multi-screen support, resolution detection and automatic window adaptation
System idle detection
- Pass
systemPreferences.getSystemIdleTime()Get the user's idle time - Can be used for auto-lock, power saving or reminder features
Multi-Language Support
i18n implementation approach
Common libraries:
i18next: Supports JSON / YAML language packs with dynamic switchingvue-i18n/react-i18next: Front-end framework integration
File structure:
locales/
en.json
zh.json
Language switching:
const i18next = require('i18next')
i18next.init({
lng: 'en',
resources: {
en: { translation: require('./locales/en.json') },
zh: { translation: require('./locales/zh.json') }
}
})
console.log(i18next.t('hello')) // 输出 hello
Can dynamically modify lng, enabling real-time language switching.
Dynamically load language packs
- For large projects, language packs can be loaded on demand:
async function setLanguage(lang) { const resources = await import(./locales/${lang}.json) i18next.addResources(lang, 'translation', resources.default) i18next.changeLanguage(lang) } - Optimize package size and reduce startup load time
Custom protocols
Electron supports registering custom protocols, allowing apps to invoke internal features or implement deep linking via a specific URL scheme.
Register a custom protocol
- Use
protocolRegister a custom protocol with a module - Can be used to load internal app resources or respond to specific URLs
const { app, protocol } = require('electron')
app.whenReady().then(() => {
protocol.registerFileProtocol('myapp', (request, callback) => {
const url = request.url.substr(7) // 去掉 'myapp://'
callback({ path: `${__dirname}/${url}` })
})
})
Explanation:
'myapp': Custom protocol namerequest.url: The full URL passed incallback({ path }): Points to a local file path, usable for loading HTML, images, etc.
Deep Linking
- Deep linking allows users to open specific app pages or features directly via a URL
- Register a system protocol:
if (!app.isDefaultProtocolClient('myapp')) { app.setAsDefaultProtocolClient('myapp') } - In macOS / Windows, clicking
myapp://note/123can trigger an app event - Handle deep links:
app.on('open-url', (event, url) => { event.preventDefault() console.log('接收到深度链接:', url) // Can parse URL and jump to internal application page }) - Windows event handling:
app.on('second-instance', (event, argv) => { const url = argv.find(arg => arg.startsWith('myapp://')) if (url) { console.log('接收到深度链接:', url) } })
Protocol handling
-
Safety:
- Validate URL content to prevent unauthorized operations
- Avoid loading malicious files or executing arbitrary commands
-
Application scenarios:
- Open specific notes, documents or pages
- Interact with Web pages and call local features
- Cross-app or cross-platform communication
-
Notes:
- On macOS, configure it in Info.plist
CFBundleURLTypes - On Windows, register the protocol in the registry
- Protocol handling logic is recommended in the main process; the renderer process only receives events