A complete guide to sending requests to Electron from a NAPI backend
Oct 12, 2025 am 07:45 AMThis document is intended to guide developers on how to send requests or messages to Electron applications from the NAPI (Node.js Addon API) backend. The article will introduce how to use Promise and callback functions to realize communication between the NAPI module and the Electron main process, and provide detailed code examples and step instructions to help developers build more efficient and flexible Electron applications.
Send message to Electron from NAPI
The core question is how to trigger events or functions in the Electron main process in the NAPI module to pass data from the backend to the frontend. Typically, NAPI functions return a value, but this is not always sufficient, especially when data needs to be pushed asynchronously to an Electron app.
Pass data using Promise
The most direct way is to use Promise. Electron's ipcMain.handle function allows you to register an asynchronous function that can be called by the rendering process. The NAPI module can pass the result to the main Electron process by returning a Promise.
Example:
Suppose you have a NAPI function SimpleFunction that receives an index and needs to send the result back to Electron.
scripts.js (rendering process):
function ClickButtonEvent(currentID) { api.SimpleFunction(parseInt(currentID)).then((data) => { // Process the data returned from NAPI console.log("Received data from NAPI:", data); }); }
main.js (main process):
const { app, BrowserWindow, Menu, ipcMain, dialog } = require('electron'); const path = require('path'); const getPcapData = require('./NAPI/build/Release/operations'); function createWindow() { const win = new BrowserWindow({ width: 1920, height: 1080, minWidth: 500, minHeight: 500, maxWidth: 1920, maxHeight: 1080, webPreferences: { preload: path.join(__dirname, 'preload.js'), }, }); win.loadFile('src/HTML/index.html'); } app.whenReady().then(() => { createWindow(); ipcMain.handle('SimpleFunction', async (event, index) => { const result = await getPcapData.SimpleFunction(index); return result; }); }); app.on('window-all-closed', () => { if (process.platform !== 'darwin') app.quit(); });
preload.js (preload script):
const { contextBridge, ipcRenderer } = require('electron'); contextBridge.exposeInMainWorld('api', { SimpleFunction: async (index) => { return await ipcRenderer.invoke('SimpleFunction', index); } });
operations.cc (NAPI module):
#include <node_api.h> #include <iostream> #define NAPI_CALL(env, call) \ do \ {\ napi_status status = (call); \ if (status != napi_ok) \ {\ const napi_extended_error_info *error_info = NULL; \ napi_get_last_error_info((env), &error_info); \ bool is_pending; \ napi_is_exception_pending((env), &is_pending); \ if (!is_pending) \ {\ const char *message = (error_info->error_message == NULL) \ ? "empty error message" \ : error_info->error_message; \ napi_throw_error((env), NULL, message); \ return NULL; } \ } \ } while (0) napi_value SimpleFunction(napi_env env, napi_callback_info info) { napi_deferred deferred; napi_value promise; NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); int index = 0; NAPI_CALL(env, napi_get_value_int32(env, args[0], &index)); // Simulate asynchronous operations // In actual applications, this will be your backend code // Here a simple timer is used to simulate asynchronous operations std::thread([env, deferred, index]() { // Simulate some calculations int result = index * 2; //Create a NAPI numerical object napi_value napi_result; NAPI_CALL(env, napi_create_number(env, result, &napi_result)); // Use napi_resolve_deferred to resolve Promise NAPI_CALL(env, napi_resolve_deferred(env, deferred, napi_result)); }).detach(); return promise; } napi_value init(napi_env env, napi_value exports) { napi_value simpleFunction; napi_create_function(env, nullptr, 0, SimpleFunction, nullptr, &simpleFunction); napi_set_named_property(env, exports, "SimpleFunction", simpleFunction); return exports; } NAPI_MODULE(NODE_GYP_MODULE_NAME, init);</iostream></node_api.h>
In this example, SimpleFunction creates a Promise and simulates an asynchronous operation in a separate thread. After the operation is completed, use napi_resolve_deferred to resolve the Promise and pass the result to the main Electron process.
Use callback function
Another way is to use callback functions. You can define a function in JavaScript and pass it as a parameter to a NAPI function. The NAPI function calls this callback function after completing the operation.
Example:
scripts.js (rendering process):
function ClickButtonEvent(currentID) { api.SimpleFunction(parseInt(currentID), (data) => { // Process the data returned from NAPI console.log("Received data from NAPI via callback:", data); }); }
preload.js (preload script):
const { contextBridge, ipcRenderer } = require('electron'); contextBridge.exposeInMainWorld('api', { SimpleFunction: (index, callback) => ipcRenderer.invoke('SimpleFunction', index).then(callback) });
main.js (main process):
const { app, BrowserWindow, Menu, ipcMain, dialog } = require('electron'); const path = require('path'); const getPcapData = require('./NAPI/build/Release/operations'); function createWindow() { const win = new BrowserWindow({ width: 1920, height: 1080, minWidth: 500, minHeight: 500, maxWidth: 1920, maxHeight: 1080, webPreferences: { preload: path.join(__dirname, 'preload.js'), }, }); win.loadFile('src/HTML/index.html'); } app.whenReady().then(() => { createWindow(); ipcMain.handle('SimpleFunction', async (event, index) => { const result = await getPcapData.SimpleFunction(index); return result; }); }); app.on('window-all-closed', () => { if (process.platform !== 'darwin') app.quit(); });
operations.cc (NAPI module):
#include <node_api.h> #include <iostream> #include <thread> #include <chrono> #define NAPI_CALL(env, call) \ do \ {\ napi_status status = (call); \ if (status != napi_ok) \ {\ const napi_extended_error_info *error_info = NULL; \ napi_get_last_error_info((env), &error_info); \ bool is_pending; \ napi_is_exception_pending((env), &is_pending); \ if (!is_pending) \ {\ const char *message = (error_info->error_message == NULL) \ ? "empty error message" \ : error_info->error_message; \ napi_throw_error((env), NULL, message); \ return NULL; \ } \ } \ } while (0) napi_value SimpleFunction(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); int index = 0; NAPI_CALL(env, napi_get_value_int32(env, args[0], &index)); // Simulate some calculations int result = index * 2; return nullptr; } napi_value init(napi_env env, napi_value exports) { napi_value simpleFunction; napi_create_function(env, nullptr, 0, SimpleFunction, nullptr, &simpleFunction); napi_set_named_property(env, exports, "SimpleFunction", simpleFunction); return exports; } NAPI_MODULE(NODE_GYP_MODULE_NAME, init);</chrono></thread></iostream></node_api.h>
Things to note:
- Ensure correct handling of errors in NAPI.
- When using NAPI in a multi-threaded environment, pay attention to thread safety.
- When using Promises or callback functions, be sure to release resources at the appropriate time.
Summarize
By using Promise or callback functions, you can easily send messages to Electron applications from NAPI modules. Which method you choose depends on your specific needs. Promises are more suitable for handling asynchronous operations, while callback functions are more suitable for simple event notifications. Understanding these two methods and choosing the appropriate method according to your application scenario can help you build more efficient and flexible Electron applications.
The above is the detailed content of A complete guide to sending requests to Electron from a NAPI backend. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

This article will introduce how to use JavaScript to achieve the effect of clicking on images. The core idea is to use HTML5's data-* attribute to store the alternate image path, and listen to click events through JavaScript, dynamically switch the src attributes, thereby realizing image switching. This article will provide detailed code examples and explanations to help you understand and master this commonly used interactive effect.

First, check whether the browser supports GeolocationAPI. If supported, call getCurrentPosition() to get the user's current location coordinates, and obtain the latitude and longitude values ??through successful callbacks. At the same time, provide error callback handling exceptions such as denial permission, unavailability of location or timeout. You can also pass in configuration options to enable high precision, set the timeout time and cache validity period. The entire process requires user authorization and corresponding error handling.

To create a repetition interval in JavaScript, you need to use the setInterval() function, which will repeatedly execute functions or code blocks at specified milliseconds intervals. For example, setInterval(()=>{console.log("Execute every 2 seconds");},2000) will output a message every 2 seconds until it is cleared by clearInterval(intervalId). It can be used in actual applications to update clocks, poll servers, etc., but pay attention to the minimum delay limit and the impact of function execution time, and clear the interval in time when no longer needed to avoid memory leakage. Especially before component uninstallation or page closing, ensure that

Nuxt3's Composition API core usage includes: 1. definePageMeta is used to define page meta information, such as title, layout and middleware, which need to be called directly in it and cannot be placed in conditional statements; 2. useHead is used to manage page header tags, supports static and responsive updates, and needs to cooperate with definePageMeta to achieve SEO optimization; 3. useAsyncData is used to securely obtain asynchronous data, automatically handle loading and error status, and supports server and client data acquisition control; 4. useFetch is an encapsulation of useAsyncData and $fetch, which automatically infers the request key to avoid duplicate requests

This tutorial explains in detail how to format numbers into strings with fixed two decimals in JavaScript, even integers can be displayed in the form of "#.00". We will focus on the use of the Number.prototype.toFixed() method, including its syntax, functionality, sample code, and key points to be noted, such as its return type always being a string.

Use the writeText method of ClipboardAPI to copy text to the clipboard, it needs to be called in security context and user interaction, supports modern browsers, and the old version can be downgraded with execCommand.

TheBestAtOrreatEamulti-LinestringinjavascriptSisingStisingTemplatalalswithbacktTicks, whichpreserveTicks, WhichpreserveReKeAndEExactlyAswritten.

AnIIFE(ImmediatelyInvokedFunctionExpression)isafunctionthatrunsassoonasitisdefined,createdbywrappingafunctioninparenthesesandimmediatelyinvokingit,whichpreventsglobalnamespacepollutionandenablesprivatescopethroughclosure;itiswrittenas(function(){/cod
