Electron: Call renderer function from main

六眼飞鱼酱① 提交于 2019-12-04 05:06:43

You can send messages from the main process to a renderer process via webContents.send as called out in the documentation here: https://github.com/atom/electron/blob/master/docs/api/web-contents.md#webcontentssendchannel-arg1-arg2-.

Here is how you do it straight from the docs:

In the main process:

// In the main process.
var window = null;
app.on('ready', function() {
  window = new BrowserWindow({width: 800, height: 600});
  window.loadURL('file://' + __dirname + '/index.html');
  window.webContents.on('did-finish-load', function() {
    window.webContents.send('ping', 'whoooooooh!');
  });
});

In index.html:

<!-- index.html -->
<html>
<body>
  <script>
    require('electron').ipcRenderer.on('ping', function(event, message) {
      console.log(message);  // Prints "whoooooooh!"
    });
  </script>
</body>
</html>

Note it is asynchronous. I am not sure how that affects things with your particular solution, but this should at least get you talking back to the renderer process.

You might use BrowserWindow.webContents.executeJavaScript like so in your main process:

// will print "whoooooooh!" in the dev console
window.webContents.executeJavaScript('console.log("whoooooooh!")');

Although you might consider it a kinda messy/dirty approach, it works. And it does not require setting up anything in the renderer process which greatly simplified things for me.
If you just want to call a particular method it would probably be quicker to write this way.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!