问题
i have a class with a Constructor and Async functions.
I have done module.exports
so that i could call my Class from my GUI.js
file and in my GUI.js
file, i have required that class, and everything works fine.
But inside my class, im trying to do this ipcRenderer.send('message', 'Hello');
And im getting this error:
TypeError: Cannot read property 'send' of undefined
is it possible to remote the ipcRenderer in my GUI.js?
Thanks.
i have required the module in my main file, and in my renderer file it sends ipcRenderer.send('startMyClass');
And in my Main file: ipcMain.on('startMyClass', (event, args) => {
const client = new myClass();
client.Start();
})
This is my class/index.js file that is being required in my main file.
const request = require('request-promise');
const cheerio = require('cheerio');
const { ipcRenderer } = require('electron')
class myClass {
constructor() {
this._jar = request.jar();
this._request = request.defaults({ jar: this._jar });
}
async Start() {
await this.Test();
};
async Test() {
ipcRenderer.send('myMessage', 'Hello');
}
}
module.exports = myClass;
EDIT: If i dont require it, and have the whole class in my main file, i can do event.sender.send('myMSG', 'hello');
But i want to do it in my class, that's NOT in the same file as my main.
回答1:
Sending message from Main to Renderer should be done by sending to a specific webContents
. That's why event.sender.send('myMSG', 'hello')
works, while ipcRenderer.send not. The latter sends from Renderer to Main as stated in docs (and also, cannot be accessed from Main process as your Error told you it's undefined).
As explainded in ipcMain
's docs you should access the webContents
you want to send to and call send
on that.
So to correct your code you can
Pass a reference to the main window to
myClass
and callsend
on thatclass myClass { constructor(args) { // ... this.mainWindow = args.win } // ... async Test() { this.mainWindow.webContents.send('myMessage', 'Hello'); } }
Or
send
to the actually focused window (BrowserWindow.getFocusedWindow()) if that fits your needsclass myClass { // ... async Test() { BrowserWindow.getFocusedWindow().webContents.send('myMessage', 'Hello'); } }
来源:https://stackoverflow.com/questions/52814192/electron-ipcrenderer-not-working-in-async-class