如何在 Electron 渲染器 window 中将消息从一个 JavaScript class/file 发送到另一个?
How to send a message in an Electron renderer window from one JavaScript class/file to another?
我正在创建一个电子应用程序,我的所有部分都被分解成单独的 classes(单独的文件)。我希望能够使用类似于 ipcRender.send 和 ipcMain.on 的东西让一个 class 与另一个交谈,但是我想在 Electron 渲染器中的两段代码之间进行通信。我怎么做?
我可以做一些愚蠢的事情,比如 mainWindow.webContents.send,使用 ipcRenderer.on 在主 window 中接收消息,然后立即使用 ipcRenderer.send 将相同的消息发送回然后通过 ipcMain.on 接收它,但这似乎有点疯狂。
有没有办法在 Electron App 中发送数据,而无需通过 Main?
我认为调用其他文件中定义的函数对您有用。
例如文件 1 中的示例:
exports.myFunction = function (arg1, arg2) {
console.log(arg1);
console.log(arg2);
};
在文件 2 中,您将拥有:
var file1 = require('./file1.js');
file1.myFunction('arg1', 'arg2');
因此,如果您要 运行 文件 2,那么它将调用文件 1 中的一个函数,该函数将 console.log arg1
和 arg2
.
你也可以用这样的变量做同样的事情:
文件 1:
exports.customVar = 'placeholder';
文件 2:
var file1 = require('./file1.js');
console.log(file1.customVar);
如果你要 运行 文件 2 它将 console.log placeholder
我发现我可以在一个 class 中使用 ipcRenderer.emit,在另一个 class 中我可以使用 ipcRenderer.on
收听消息
我正在创建一个电子应用程序,我的所有部分都被分解成单独的 classes(单独的文件)。我希望能够使用类似于 ipcRender.send 和 ipcMain.on 的东西让一个 class 与另一个交谈,但是我想在 Electron 渲染器中的两段代码之间进行通信。我怎么做?
我可以做一些愚蠢的事情,比如 mainWindow.webContents.send,使用 ipcRenderer.on 在主 window 中接收消息,然后立即使用 ipcRenderer.send 将相同的消息发送回然后通过 ipcMain.on 接收它,但这似乎有点疯狂。
有没有办法在 Electron App 中发送数据,而无需通过 Main?
我认为调用其他文件中定义的函数对您有用。
例如文件 1 中的示例:
exports.myFunction = function (arg1, arg2) {
console.log(arg1);
console.log(arg2);
};
在文件 2 中,您将拥有:
var file1 = require('./file1.js');
file1.myFunction('arg1', 'arg2');
因此,如果您要 运行 文件 2,那么它将调用文件 1 中的一个函数,该函数将 console.log arg1
和 arg2
.
你也可以用这样的变量做同样的事情:
文件 1:
exports.customVar = 'placeholder';
文件 2:
var file1 = require('./file1.js');
console.log(file1.customVar);
如果你要 运行 文件 2 它将 console.log placeholder
我发现我可以在一个 class 中使用 ipcRenderer.emit,在另一个 class 中我可以使用 ipcRenderer.on
收听消息