我有一个使用 neon rust 创建的 Nodejs 模块,它使用 JsBox 和队列异步功能。我还有一个 Electron React 应用程序,我当前的 mainjs 看起来像这样:
function createWindow() {
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
contextIsolation: true,
webSecurity: false,
preload: path.join(__dirname, 'preload.js')
}
})
mainWindow.loadURL(
isDev ? "http://localhost:3000" : `file://${path.join(__dirname, "../build/index.html")}`
)
// Open the DevTools.
// mainWindow.webContents.openDevTools()
}
在 preloadjs 中,我已将模块映射到这样的类:
const shinny_spoon_service = require('../../shiny-spoon-service/lib/index')
class Cracker {
constructor(hash, threads, callback) {
this._cracker = shinny_spoon_service.cracker_new(hash, threads, callback)
}
get_counter() {
return shinny_spoon_service.get_counter(this._cracker)
}
cracker_crack_using_password_file(algorithm,file_path,buff_size){
return shinny_spoon_service.cracker_crack_using_password_file(this._cracker,algorithm,file_path,buff_size)
}
}
当我使用上下文桥将类传递给渲染器进程时
contextBridge.exposeInMainWorld(
"api",
{
shiny_spoon: shinny_spoon_service,
nativeImage: nativeImage,
Cracker: Cracker,
send: (channel, data) => {
// whitelist channels
let validChannels = ["getFile", "open-error-dialog"];
if (validChannels.includes(channel)) {
ipcRenderer.send(channel, data);
}
},
receive: (channel, func) => {
let validChannels = ["result-get-file", 'opened-error-dialog'];
if (validChannels.includes(channel)) {
// Deliberately strip event as it includes `sender`
ipcRenderer.on(channel, (event, args) => func(event, args));
}
},
sendSync: (channel, data) => {
// whitelist channels
let validChannels = ["getFile", "saveFile", "chooseFile"];
if (validChannels.includes(channel)) {
let result = ipcRenderer.sendSync(channel, data);
return result
}
},
}
)
我收到如图所示的错误 我想与渲染器进程中的类进行交互,但我不知道如何去做
您无法在 Electron 中使用 contextBridge 传递复杂的对象和类。 Electron 将剥离方法和构造函数。在您的示例中,如果您想使用 new,则需要创建一个返回实例本身及其方法的函数。
//...preload
Cracker: {
createCrackerInstance : (...args) => {
const cracker = new Cracker(...args)
return {cracker: cracker
getAttribute1: () => cracker.getAttribute1()
//other methods
}
}