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 can make applications more professional and powerful.
Native Node.js module integration
node-gyp usage
- node-gypIs a Node.js native module compilation tool, supports C/C++ module compilation
Installation:
npm install -g node-gyp
- Initialize project:
node-gyp configure node-gyp build
- Output
.nodefile, 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
- Usage
electron-rebuildTools:npm install --save-dev electron-rebuild npx electron-rebuild
- Ensure the module is compatible with the current Electron version
Troubleshooting common issues
- ABI incompatibility: Electron uses different Node versions, requiring
electron-rebuild - Compilation failed:Checks C++ CompileEnvironment(Windows NeedInstallation Visual Studio Build Tools,macOS Need Xcode Command Line Tools)
- Path issue: Ensure the module path is correct, use absolute paths to load
.nodeFile
Deep integration with the system
System theme detection
- Detect dark/light theme:
const { nativeTheme } = require('electron') console.log(nativeTheme.shouldUseDarkColors) nativeTheme.on('updated', () => { console.log('主题更新:', nativeTheme.shouldUseDarkColors) }) - Prevent system sleep:
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
- Through
systemPreferences.getSystemIdleTime()Get user idle time - Can be used for auto screen lock, power saving, or reminder functions
Multilingual support
i18n implementation approach
Common libraries:
i18next: Support JSON/YAML language packs, dynamic switchingvue-i18n/react-i18nextFrontend 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 be dynamically modifiedlng, 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, reduce startup loading time
Custom protocol
Electron supports registering custom protocols, allowing the application to call internal functions or implement deep linking through specific URL schemes.
Register custom protocol
- Usage
protocolModule registers custom protocol - Can be used to load internal application 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}` })
})
})
Description:
'myapp': Custom protocol namerequest.url: Full URL passed incallback({ path }): Points to a local file path, can be used to load HTML, images, etc.
Deep Linking
- Deep links allow users to directly open specific pages or features of an application via URL
- Register system protocol:
if (!app.isDefaultProtocolClient('myapp')) { app.setAsDefaultProtocolClient('myapp') } - On macOS / Windows, click
myapp://note/123Can trigger application events - Handle deep links:
app.on('open-url', (event, url) => { event.preventDefault() console.log('接收到深度链接:', url) // 可解析 URL 跳转到应用内部页面 }) - Windows event handling:
app.on('second-instance', (event, argv) => { const url = argv.find(arg => arg.startsWith('myapp://')) if (url) { console.log('接收到深度链接:', url) } })
Protocol handling
-
Security:
- Validate URL content to prevent unauthorized operations
- Avoid loading malicious files or executing arbitrary commands
-
application scenarios:
- Open a specific note, document, or page
- Interact with web pages, invoke local features
- Cross-application or cross-platform communication
-
Notes:
- macOS requires configuration in Info.plist
CFBundleURLTypes - Windows requires registering the protocol in the registry
- Protocol handling logic should be placed in the main process; the renderer process only receives events
- macOS requires configuration in Info.plist