'Electron renderer.js listen app.js and preload.js

I need send element from app.js to renderer.js (index.html) using preload.js, without calling the function by renderer.js.

Is it possible?

Below the electron ipc and contextbridge code.

renderer.js

window.onload = () => {
  const counter = document.querySelector('h2');
  setInterval(() =>{
    api.get(counter.innerText).then(res => {
        counter.innerText = res
    })
  }, 1000)
}

preload.js

const {contextBridge, ipcRenderer} = require('electron')

contextBridge.exposeInMainWorld('api', {
  get: arg => ipcRenderer.invoke('get', arg),
})

app.js

const {app, BrowserWindow, ipcMain} = require('electron')
const path = require('path')

app.whenReady().then(() => {
  const mainWindow = new BrowserWindow({
    width: 500,
    height: 500,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  })

  // ipc response on request
  ipcMain.handle('get', (event, arg) => {
    return ++arg
  })

  mainWindow.loadFile('index.html')

  // Open the DevTools.
  //mainWindow.webContents.openDevTools()
})

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    <title>IPC Example</title>
  </head>
  <body>
    <h1>Wait on response...</h1>
    <h2>0</h2>

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


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source