javascript - Creating invisible window from main process to compute function in Electron -
i trying write electron program in main process creates invisible window, sends number window, window computes factorial , sends back.
this in main process:
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} ${output}` console.log(message); }) } the function gets called in main process by:
app.on('ready', () => { // creates different window here invisiblewindow(); }); this inv.html file:
<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> now after have added program, every time when start through terminal, not terminate when other (visible) windows closed. guess because invisible window still opened because did not receive compute-factorial event.
what doing wrong?
this because of race condition. electron docs:
event: 'did-finish-load'
emitted when navigation done, i.e. spinner of tab has stopped spinning, , onload event dispatched.
you can try settimeout:
win.webcontents.on('did-finish-load', function () { settimeout(() => { const input = 100; win.webcontents.send('compute-factorial', input); }, 3000); }); the main process not know when dom ready. can this.
send main process "dom-is-ready" event.
inv.html
ipc.send('dom-is-ready'); paste 'did-finish-load' code '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} ${output}` console.log(message); }); }
Comments
Post a Comment