YouTip LogoYouTip

Electron Advanced

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 your application more professional and powerful. * * * ## Native Node Module Integration ### Using node-gyp * **node-gyp** is the Node.js native module compilation tool, supporting C/C++ module compilation * Installation: npm install -g node-gyp * Initialize project: node-gyp configure node-gyp build * Outputs a `.node` file, which can be directly loaded in Electron: const native = require('./build/Release/native.node') ### Compiling Native Modules * Native modules must be compiled against Electron's Node version and ABI * Use the `electron-rebuild` tool: npm install --save-dev electron-rebuild npx electron-rebuild * Ensure the module is compatible with the current Electron version ### Common Issues and Solutions * **ABI Incompatibility**: Electron uses a different Node version, requiring `electron-rebuild` * **Compilation Failure**: Check the C++ compilation environment (Windows requires Visual Studio Build Tools, macOS requires Xcode Command Line Tools) * **Path Issues**: Ensure the module path is correct, use absolute paths to load `.node` files * * * ## Deep System Integration ### System Theme Detection * Detect dark/light theme: const { nativeTheme } = require('electron') console.log(nativeTheme.shouldUseDarkColors) nativeTheme.on('updated', () => { console.log('Theme updated:', nativeTheme.shouldUseDarkColors)}) * Prevent system sleep: const { powerSaveBlocker } = require('electron')const id = powerSaveBlocker.start('prevent-display-sleep') powerSaveBlocker.stop(id) * Detect power state: 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 * Get user idle time via `systemPreferences.getSystemIdleTime()` * Can be used for auto-lock, energy saving, or reminder features * * * ## Multi-language Support ### i18n Implementation Solutions Commonly used libraries: * `i18next`: Supports JSON / YAML language packs, dynamic switching * `vue-i18n` / `react-i18next`: Frontend 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')) // Outputs hello You can dynamically modify `lng` to switch languages in real-time. ### Dynamically Loading 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)} * Optimizes package size and reduces startup loading time * * * ## Custom Protocols Electron supports registering custom protocols, allowing applications to invoke internal functions via specific URL schemes or implement Deep Linking. ### Registering Custom Protocols * Use the `protocol` module to register custom protocols * 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) // Remove 'myapp://' callback({ path: `${__dirname}/${url}` }) })}) Explanation: * `'myapp'`: Custom protocol name * `request.url`: The incoming full URL * `callback({ path })`: Points to a local file path, can be used to load HTML, images, etc. * * * ### Deep Linking * Deep linking allows users to directly open specific pages or functions within the app via a URL * Register system protocol: if (!app.isDefaultProtocolClient('myapp')) { app.setAsDefaultProtocolClient('myapp')} * In macOS / Windows, clicking `myapp://note/123` can trigger application events * Handle deep links: app.on('open-url', (event, url) => { event.preventDefault() console.log('Received deep link:', url) // Can parse URL to navigate to internal app page}) * Windows event handling: app.on('second-instance', (event, argv) => { const url = argv.find(arg => arg.startsWith('myapp://')) if (url) { console.log('Received deep link:', url) }}) ### Protocol Handling * **Security**: * Validate URL content to prevent unauthorized operations * Avoid loading malicious files or executing arbitrary commands * **Use Cases**: * Open specific notes, documents, or pages * Interact with web pages, invoke local functions * Cross-application or cross-platform communication * **Notes**: * macOS requires configuring `CFBundleURLTypes` in Info.plist * Windows requires registering the protocol in the registry * Protocol handling logic is recommended to be placed in the main process, with the renderer process only receiving events
← Vue ElectronElectron Release β†’