Electron:从main调用渲染器功能

Gor*_*man 7 javascript electron

我在localstorage中有一些必须删除的数据app.quit().但我认为从主流程中无法做到这一点.

有没有办法从中调用renderer函数main

我知道var remote = require('remote');但似乎只是在错误的方向.

Sha*_*ski 14

您可以通过webContents.send将主进程的消息发送到渲染器进程,如以下文档中所述:https://github.com/atom/electron/blob/master/docs/api/web-contents.md# webcontentssendchannel-arg1-arg2-.

以下是您直接从文档中执行此操作的方法:

在主要过程中:

// 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!');
  });
});
Run Code Online (Sandbox Code Playgroud)

在index.html中:

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

注意它是异步的.我不确定这会如何影响您的特定解决方案,但这至少应该让您回到渲染器过程.


Joh*_*150 7

您可以在主过程中像这样使用BrowserWindow.webContents.executeJavaScript

// will print "whoooooooh!" in the dev console
window.webContents.executeJavaScript('console.log("whoooooooh!")');
Run Code Online (Sandbox Code Playgroud)

尽管您可能认为这是一种杂乱/肮脏的方法,但是它可以工作。而且它不需要在渲染器过程中进行任何设置,而这大大简化了我的工作。
如果您只想调用特定的方法,则编写这种方法可能会更快。

  • 这是从菜单项触发页面中的操作的更好方法 (2认同)