Communicating main process with rendering process 15
From the index, we activate the integration with Node and consume them; we define an event in which, when loading the window (web page) we transmit the data via a message:
index.js
const { chats, contacts } = require('./data')
***
function createWindow(){
let win = new BrowserWindow({
width: 1300,
height:900,
webPreferences:{
nodeIntegration: true,
contextIsolation: false
}
})
win.loadFile("index.html")
win.webContents.openDevTools()
win.webContents.on('did-finish-load', () => {
win.webContents.send('fs-chats',chats)
win.webContents.send('fs-contacts',contacts)
});
}
From the web page, thanks to the fact that we activated the integration with Node, we can import the ipcRenderer module, in order to communicate with the main process, specifically, we are interested in creating a listener (listener) to receive the data sent from the main process:
index.html
<script>
const { ipcRenderer } = require('electron')
function createContacts(contacts) {
var lis = ''
contacts.forEach((c) => {
lis += `<li class="p-2 card mt-2">
<div class="card-body">
<div class="d-flex">
<div>
<img class="rounded-pill me-3" width="60"
src="${c.image}">
</div>
<div>
<p class="fw-bold mb-0 text-light">${c.name}</p>
<p class="small text-muted">${c.last_chat[0]['message']}</p>
</div>
<div>
<p class="small text-muted">${c.last_chat[0]['date']}</p>
<span class="badge bg-danger rounded-pill float-end">1</span>
</div>
</div>
</div>
</li>`
})
document.querySelector('.contact').innerHTML = lis;
}
function createChats(chats) {
var lis = ''
chats.forEach((c) => {
lis += ` <div class="d-flex chat">
<div class="w-75 ">
<div class="card bg-dark">
<div class="card-body text-light">
${c.chat.message}
</div>
</div>
<p class="small text-muted float-end">${c.chat.date}</p>
</div>
<div class="w-25 d-flex align-items-end">
<img class="rounded-pill ms-3 avatar" src="${c.user.image}"/>
</div>
</div>`
})
document.querySelector('.chats').innerHTML = lis;
}
ipcRenderer.on('fs-chats',(event, chats)=>{
createChats(chats)
})
ipcRenderer.on('fs-contacts',(event, contacts)=>{
createContacts(contacts)
})
</script>
The next thing we are going to do is initialize listings between the main process and the rendering process in Electron
Remember that the previous material is part sobre mi curso completo sobre Electron.js
- Andrés Cruz
Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter