nik*_*ssc 2 javascript electron
我正在尝试编写一个 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);
})
}
Run Code Online (Sandbox Code Playgroud)
该函数在主进程中通过以下方式调用:
app.on('ready', () => {
// creates different window here
invisibleWindow();
});
Run Code Online (Sandbox Code Playgroud)
这是 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>
Run Code Online (Sandbox Code Playgroud)
现在,在我将其添加到程序中后,每次通过终端启动它时,即使所有其他(可见)窗口都关闭,它也不会自行终止。我猜这是因为隐形窗口仍然打开,因为它没有收到事件compute-factorial。
我究竟做错了什么?
这是因为一个race condition. 电子文档:
事件:“完成加载”
导航完成时发出,即选项卡的旋转器停止旋转,并且调度 onload 事件。
你可以尝试一下setTimeout:
win.webContents.on('did-finish-load', function () {
setTimeout(() => {
const input = 100;
win.webContents.send('compute-factorial', input);
}, 3000);
});
Run Code Online (Sandbox Code Playgroud)
主进程不知道 DOM 何时准备好。你可以做这样的事情。
向您的主进程发送“dom-is-ready”事件。
索引.html
ipc.send('dom-is-ready');
Run Code Online (Sandbox Code Playgroud)
将您的'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);
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10054 次 |
| 最近记录: |