Electron - How to know when renderer window is ready

旧时模样 提交于 2019-12-08 14:50:27

问题


In my main process I create a renderer window:

var mainWindow = new BrowserWindow({
    height: 600,
    width: 800,
    x: 0,
    y: 0,
    frame: false,
    resizable: true
});
mainWindow.openDevTools();
mainWindow.loadURL('file://' + __dirname + '/renderer/index.html');

Then I want to communicate with it in some way:

mainWindow.webContents.send('message', 'hello world');

However the main window doesn't receive this message because it isn't fully done being created at the time I attempt to send it.

I have temporarily solved this by wrapping the latter code in a setTimeout() but that is most definitely not the right way to resolve a race condition.

Is there a callback for when the main window is ready? I tried the 'ready-to-show' event mentioned in the docs but it did not work.


回答1:


A listener on "mainWindow" doesn't worked for me. I used instead "mainWindow.webContents".

mainWindow.webContents.once('dom-ready', () => {});



回答2:


Have a look at the did-finish-load event mentioned in the Electron browser-window documentation.

mainWindow.once('did-finish-load', () => {
   // Send Message
})

There seems to be a dom-ready event too.




回答3:


not mentioned in the previous answers, loadURL returns a promise that resolves at the same time the 'did-finish-load' event is fired; i.e., they're essentially equivalent, except one's a promise, and the other's a callback.




回答4:


Check this: https://github.com/electron/electron/blob/master/docs/api/web-contents.md

You can use this event to know if your windows is ready in you main.js [CASE 1], but if want to know when your page is full loaded you should add an event in your index.html [CASE 2] and then you can attach a function that send a message to his parent Main.js telling him, he is ready, using IPCrenderer and IPCmain

CASE 1

main.js:

mainWindows.webContents.on('did-finish-load',WindowsReady);

function WindowsReady() {
    console.log('Ready');
}

CASE 2

html:

<script>
const {ipcRenderer} = require('electron');
document.addEventListener('DOMContentLoaded',pageLoaded);

 function pageLoaded(){
     alert('The page is loade');
     ipcRenderer.send('Am_I_Ready',"Im ready");
 }
</script>

Main.js:

const {ipcMain} = electron;

ipcMain.on('Am_I_Ready', doSomething)

function doSomething(){
  console.log('Everything is ready.');
}



回答5:


These days, you use the "ready-to-show" event.

https://electronjs.org/docs/api/browser-window#using-ready-to-show-event



来源:https://stackoverflow.com/questions/42284627/electron-how-to-know-when-renderer-window-is-ready

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!