我正在尝试编写一个 Electron 程序,其中主进程创建一个不可见的窗口,向该窗口发送一个数字,该窗口计算阶乘,然后将其发送回来。
这是在主进程中:
function invisibleWindow() {
const invisPath = 'file://' + path.join(__dirname, 'files/html/inv.html')
let win = new BrowserWindow({ width: 400, height: 400, show: false })
win.loadURL(invisPath)
win.webContents.on('did-finish-load', function () {
const input = 100;
win.webContents.send('compute-factorial', input);
})
ipcMain.on('factorial-computed', function (event, input, output) {
const message = `The factorial of ${input} is ${output}`
console.log(message);
})
}
该函数在主进程中通过以下方式调用:
app.on('ready', () => {
// creates different window here
invisibleWindow();
});
这是 inv.html 文件:
<html>
<script type="text/javascript">
const ipc = require('electron').ipcRenderer
const BrowserWindow = require('electron').remote.BrowserWindow
ipc.on('compute-factorial', function (event, number) {
const result = factorial(number)
ipcRenderer.send('factorial-computed', number, result)
window.close()
})
function factorial (num) {
if (num === 0) return 1
return num * factorial(num - 1)
}
</script>
</html>
现在,在我将其添加到我的程序中后,每次我通过终端启动它时,即使所有其他(可见)窗口都关闭,它也不会自行终止。我猜这是因为隐形窗口仍然打开,因为它没有收到 compute-factorial
事件。
我做错了什么?
最佳答案
这是由于竞争条件
造成的。
Electron 文档:
Event: 'did-finish-load'
Emitted when the navigation is done, i.e. the spinner of the tab has stopped spinning, and the onload event was dispatched.
您可以使用setTimeout
尝试一下:
win.webContents.on('did-finish-load', function () {
setTimeout(() => {
const input = 100;
win.webContents.send('compute-factorial', input);
}, 3000);
});
主进程不知道 DOM 何时准备好。 你可以做这样的事情。
向您的主进程发送“dom-is-ready”事件。
inv.html
ipc.send('dom-is-ready');
将您的'did-finish-load'代码粘贴到'dom-is-ready'中。
main.js
function invisibleWindow() {
const invisPath = 'file://' + path.join(__dirname, 'files/html/inv.html');
const win = new BrowserWindow({
width: 400,
height: 400,
show: false
});
win.loadURL(invisPath);
win.webContents.on('did-finish-load', function () {
win.show();
});
ipcMain.on('dom-is-ready', function (event) {
const input = 100;
win.webContents.send('compute-factorial', input);
});
ipcMain.on('factorial-computed', function (event, input, output) {
const message = `The factorial of ${input} is ${output}`
console.log(message);
});
}
关于javascript - 在 Electron 中创建从主进程到计算函数的不可见窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46149702/