Electron调用nodejs的cpp .node扩展【非安全】

Electron调用nodejs的cpp .node扩展【非安全】

环境:

复制代码
electron: 30.1.1
nodejs: 20.14.0

前言

Electron中可以非常容易的调用nodejs的js代码,但是对于cpp .node扩展需要一定的配置才能调用,下面介绍一种最简单的cpp扩展的调用方法,该方法的优点是调用简单,缺点是会降低应用程序的安全性,生产环境中需谨慎使用。

代码

复制代码
$ tree
.
+--- build
|   +--- Release
|   |   +--- addon.node
+--- addon.cpp
+--- binding.gyp
+--- CMakeLists.txt
+--- index.html
+--- index.js
+--- package.json

index.html

复制代码
<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8" />
  <title>Hello Electron</title>
  <meta http-equiv="Content-Security-Policy" content="default-src 'self' 'unsafe-inline';">
</head>

<body>
  <p id="version"></p>
  <p id="napi"></p>

  <script>
    let info = `electron: ${process.versions.electron}, nodejs: ${process.versions.node}, chrome: ${process.versions.chrome}, v8: ${process.versions.v8}`;
    document.getElementById("version").innerHTML = info;
    console.log(info);

    const addon = require('./build/Release/addon.node');
    info = addon.hello();
    document.getElementById("napi").innerHTML = info;
    console.log(info);
  </script>
</body>

</html>

index.js

复制代码
const { app, BrowserWindow } = require('electron/main');
// app.commandLine.appendSwitch('remote-debugging-port', '9222');

const createWindow = () => {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    }
  })

  win.loadFile('index.html');
}

app.whenReady().then(() => {
    createWindow();
})

addon.cpp

复制代码
#include <node_api.h>

static napi_value helloMethod(napi_env env, napi_callback_info info)
{
    napi_value result;
    napi_create_string_utf8(env, "hello world from napi", NAPI_AUTO_LENGTH, &result);

    return result;
}

static napi_value Init(napi_env env, napi_value exports)
{
    napi_property_descriptor desc = {"hello", 0, helloMethod, 0, 0, 0, napi_default, 0};

    napi_define_properties(env, exports, 1, &desc);

    return exports;
}

NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)

binding.gyp

复制代码
{
  "targets": [
    {
      "target_name": "addon",
      "sources": [ "addon.cpp" ]
    }
  ]
}

CMakeLists.txt

复制代码
cmake_minimum_required(VERSION 2.8.12)

project(addon)

message(STATUS "operation system is ${CMAKE_SYSTEM}")

add_definitions(-std=c++11)

include_directories(${CMAKE_JS_INC})
include_directories(.)

file(GLOB SOURCE_FILES addon.cpp)

add_library(${PROJECT_NAME} SHARED ${SOURCE_FILES} ${CMAKE_JS_SRC})

set_target_properties(${PROJECT_NAME} PROPERTIES PREFIX "" SUFFIX ".node")

target_link_libraries(${PROJECT_NAME} ${CMAKE_JS_LIB})

package.json

复制代码
{
  "name": "my-electron-app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "electron ."
  }
}

编译

复制代码
node-gyp configure build

结果

复制代码
electron: 30.1.1, nodejs: 20.14.0, chrome: 124.0.6367.243, v8: 12.4.254.20-electron.0

hello world from napi

禁用 contextIsolation 和启用 nodeIntegration,会降低应用的安全性。务必谨慎使用,并确保你信任加载的所有代码和资源。

相关推荐
LDM>W<5 小时前
Electron下载失败
前端·javascript·electron
EndingCoder5 小时前
Electron 新特性:2025 版本更新解读
前端·javascript·缓存·electron·前端框架·node.js·桌面端
小圣贤君1 天前
小说创作中的时间轴体验设计:事序图交互与用户体验优化
electron·vue·甘特图·时序图·写作软件
ayaya_mana1 天前
BilldDesk:基于Vue3+WebRTC+Nodejs+Electron的开源远程桌面控制
electron·开源·webrtc
卸任1 天前
Electron运行环境判断(是否在虚拟机中)
前端·react.js·electron
F2E_zeke1 天前
使用electron将vue3网页项目包装成pc客户端
javascript·vue.js·electron
TangAcrab1 天前
记一次 electron 添加 检测 终端编码,解决终端打印中文乱码问题
前端·javascript·electron
EndingCoder1 天前
Electron 高级 UI:集成 React 或 Vue.js
react.js·ui·electron·前端框架
EndingCoder1 天前
离线应用开发:Service Worker 与缓存
前端·javascript·缓存·性能优化·electron·前端框架
太空游走的鱼2 天前
Vue3 + Vite + Element Plus web转为 Electron 应用,解决无法登录、隐藏自定义导航栏
javascript·electron·vue3·管理系统·element plsu