要将消息从main thread 发送到特定的render thread,需要使用WebContents.send。需要了解Inter-Process Communication 和Context Isolation。
除了主线程和渲染线程之间的通信之外,在两个以上脚本之间共享“窗口”对象的最简单方法是使用“getter”函数。
在下面的示例中,文件myWindow.js 创建了窗口并将其存储在名为myWindow 的变量中,因此可以通过使用导出的get() 函数随时返回。
myWindow.js(主线程)
const electronBrowserWindow = require('electron').BrowserWindow;
const nodePath = require('path');
let myWindow;
function create() {
// Create the window.
myWindow = new electronBrowserWindow ({
x: 0,
y: 0,
width: 800,
height: 600,
show: false,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: nodePath.join(__dirname, 'preload.js')
}
})
// Load the window.
myWindow.loadFile(nodePath.join(__dirname, 'window.html'))
.then(() => { window.show(); })
// Return window should the script creating the window need it.
return myWindow;
}
function get() {
return myWindow;
}
// Export the publicly available functions.
module.exports = {create, get};
在这个答案中,我假设您已经正确配置了 preload.js 脚本。 IE:一个主渲染线程通道,名为build-console-log。
要引用 Electron myWindow 对象,请包含 myWindow.js 模块并使用 appWindow.get() 函数。
当buildProject()函数被调用时,通过build-console-log频道发送消息。
otherFile.js(主线程)
const nodePath = require('path');
const appWindow = require(nodePath.join(__dirname, 'myWindow'));
function buildProject(project) {
// Send message to render thread.
appWindow.get().webContents.send('build-console-log', 'building ' + project);
}
module.exports = {buildProject};
确保 html 页面正在通过build-console-log 频道监听消息。
window.html(渲染线程)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Title</title>
<link rel="stylesheet" href="index.css" />
</head>
<body>...</body>
<script>
(function() => {
window.ipcRender.receive('build-console-log', (event, message) => { display(message); }
})();
display(message) { console.log(message); }
</script>
</html>
现在,让我们向渲染发送消息。
message.js(主线程)
const nodePath = require('path');
const otherFile = require(nodePath.join(__dirname, 'otherFile'));
// Message the render.
otherFile.buildProject('project name');
渲染中的控制台输出应该是building project name。