Communicate with in Electron

2019-04-05 08:26发布

I have a <webview> in my Electron app. I'd like to have safe "foreign" communication, the way I would with an iframe through postMessage. So for example:

webview.executeJavaScript("window.parent.postMessage('all done!')");

Is my only choice for communication with this subwebview to turn on nodeIntegration so that I can use sendToHost? Turning on all of nodeIntegration just for this one feature seems like overkill.

标签: electron
1条回答
倾城 Initia
2楼-- · 2019-04-05 08:30

You can access Electron APIs in the webview preload script, including IPC, even when nodeIntegration is disabled. Your preload script can inject functions into the global namespace that will then be accessible within the page loaded in the webview. A simple example:

webview-preload.js:

const { ipcRenderer } = require('electron')    

global.pingHost = () => {
  ipcRenderer.sendToHost('ping')
}

webview-index.html:

<script>
  pingHost()
</script>

window-index.html:

<script>
  const webview = document.getElementById('mywebview')
  webview.addEventListener('ipc-message', event => {
    // prints "ping"
    console.log(event.channel)
  })
</script>
查看更多
登录 后发表回答