I have just started learning electron
. I was wondering if it's a good idea to use ipcRenderer
calls inside preload script, i.e.:
const sc = require('./StaticContent');
const dc = require('./DynamicContent');
const { ipcRenderer } = require('electron');
window.addEventListener('DOMContentLoaded', () => {
document.getElementById('view').innerHTML = sc.getInfoPage();
document.getElementById('menu-info').addEventListener('click', (evt) => {
ipcRenderer.send('load-info');
});
ipcRenderer.on('get-view', (event, arg) => {
document.getElementById('view').innerHTML = arg;
});
});
Every tutorial I read uses external js
file to manage ipcRenderer
calls and doesn't even bother with preload
script. But it works.
I can also achieve what I want without ipc
calls:
window.addEventListener('DOMContentLoaded', () => {
document.getElementById('view').innerHTML = sc.getInfoPage();
document.getElementById('menu-info').addEventListener('click', (evt) => {
document.getElementById('view').innerHTML = sc.getInfoPage();
});
});
Which one is better? I have no idea of any negative impact, I just want to learn best practice from the beginning.
Yes, you can absolutely use ipcRenderer
inside of the preload script, and you can see an example of that here.
Whether you should or not ultimately depends on your goal.
If you need to have the main process do something, then you have to use ipc to send a message from the preload script to the main process. If you don't need the main process for anything and are OK with just executing your code in the context of the renderer that's running the preload script, then you can feel free to run your code there.
In your case, it probably makes sense to just do all the DOM manipulation in the preload script. Sending a message to the main process only to have it send a message back to the renderer to execute your get-view
handler is just extra work for no reason.