How the ipc send message works?


#1

hi guys.

i find one thing that I do not understand, look at the very simple code below:

main process:

mainWindow = new BrowserWindow({width: 800, height: 600})

  // and load the index.html of the app.
mainWindow.loadURL(`file://${__dirname}/index.html`)

var wc = mainWindow.webContents;
wc.openDevTools();
wc.on('dom-ready', function(){
  console.log('dom-ready, [from main process]');
  wc.send('dom-ready', 'ready');
    console.log(`web page is loading: ${wc.isLoading()}, [from main process]`);
})

renderer process:

var ipc = require('electron').ipcRenderer;
ipc.on('dom-ready', function(e, str){
  console.log(str);
});

the html file is like:

...
  <script src="./renderer.js">
  </script>
...

the question is:
in the renderer process, ‘ready’ message can be printed.
but in my comprehension, when the dom-ready event happened, the renderer.js script has not loaded, so why the renderer ipc can catch the dom-ready channel message?


#2

Actually, the script has probably already loaded. See, scripts are executed before continuing onto the next item in the DOM. According to MDN, synchronous JavaScript pauses DOM parsing. Setting up a listener for the event is a synchronous action. That’s why the listener catches the event, because it’s listening before the DOM is done parsing.


#3

Well very thx for your reply.
I get it!