Alexei Romanov
Alexei Romanov

Reputation: 21

How I can get result of event in browserView?

How I can get result of event in browserView? I have:

browserView.webContents.executeJavaScript('
  let btn = document.createElement("button")
  btn.innerHTML = "Click Me"
  btn.addEventListener("click", function () {
    return "Button is clicked"
  })
  document.body.appendChild(btn)
').then(r=> console.log(r))

What I need to do to get "Button is clicked" after click on button in main process and add to variable?

Upvotes: 0

Views: 731

Answers (2)

Alexei Romanov
Alexei Romanov

Reputation: 21

In my solutions we need preload for browserView:

const browserView = new BrowserView({
            webPreferences: {
                preload: path.join(__dirname, 'preload.js') 
            }
        })

preload.js

const {ipcRenderer} = require('electron')

window.addEventListener('DOMContentLoaded', () => {
  let btn = document.createElement("button")
  btn.innerHTML = "Click Me"
  btn.addEventListener("click", function () {
    ipcRenderer.send('message','button is clicked')
  })
  document.body.appendChild(btn)
})

And... it works! In main proccess with ipcMain.on we received "button is clicked"

Upvotes: 1

windmaomao
windmaomao

Reputation: 7670

Basically you need to have to find a way to call ipcRenderer in the view, ex. ipcRenderer.send('message', 'hi'). And in the main thread, you can do ipcMain.on('message', () => {}).

But for your question, how do you access ipcRenderer? Try

  browserView.webContents.executeJavaScript('
    const { ipcRenderer } = require('electron')
    ipcRenderer.send('message', 'hi')

And in the index.js

const { ipcMain } = require('electron')

ipcMain.on('message', (e, t) => {
  console.log(t)
})

Upvotes: 0

Related Questions