Reputation: 13723
I am trying to send some data from the Main Process to the Renderer (The browser view), and have seemingly run into a roadblock.
When I call window.webContents.send, the event can be trapped only in the preload. I want to modify the data on the renderer (Modify the contents of the screen) using this function.
Preload seems a pretty one-way street, where I can call methods from the html view, but how do I call the html view from the preload?
Or how do I send information from the Main to the renderer view and modify html there?
Any suggestions?
Upvotes: 3
Views: 1725
Reputation: 1255
When I call window.webContents.send, the event can be trapped only in the preload. I want to modify the data on the renderer (Modify the contents of the screen) using this function.
You can expose functions via context bridge in the preload script. This will allow your renderer to set a listener that receives messages from the main process.
Here's a toy example of a counter that will increment a counter in your HTML:
// main process
mainWindow.webContents.send('update-counter', 1)
// preload
const { contextBridge, ipcRenderer } = require('electron')
contextBridge.exposeInMainWorld('electronAPI', {
handleCounter: (callback) => ipcRenderer.on('update-counter', callback)
})
// renderer process
const counter = document.getElementById('counter')
window.electronAPI.handleCounter((event, value) => {
const oldValue = Number(counter.innerText)
const newValue = oldValue + value
counter.innerText = newValue
})
<!--html-->
<body>
Current value: <strong id="counter">0</strong>
<script src="./renderer.js"></script>
</body>
Upvotes: 7