在 Electron 中将数据传递给 Windows

Passing Data to Windows in Electron

我正在学习 Electron 并使用多个 windows 和 IPC。在我的主脚本中,我有以下内容:

var storeWindow = new BrowserWindow({
  width: 400,
  height: 400,
  show: false
});

ipc.on('show-store-edit', function(event, store) {
  console.log(store);
  storeWindow.loadURL('file://' + __dirname + '/app/store.html');
  storeWindow.show();
});

在我的主要 window 脚本中,我在点击事件处理程序中有以下内容,拉入商店列表:

$.getJSON("http://localhost:8080/stores/" + item.id).done(function(store) {
   ipc.send('show-store-edit', store);
});

在控制台上,我正在打印来自我的服务器的商店数据。我不清楚的是如何将这些数据放入我的 storeWindow:store.html 的视图中。我什至不确定我是否正确处理了事件的顺序,但它们会是:

在后者中,我不确定如何获得从 storeWindow's 脚本获取商店所需的 ID。

要将事件发送到特定的 window,您可以使用 webContents.send(EVENT_NAME, ARGS) (see docs)。 webContents 是 window 实例的 属性:

// main process
storeWindow.webContents.send('store-data', store);

要侦听正在发送的此事件,您需要 window 进程(渲染器)中的侦听器:

// renderer process
var ipcRenderer = require('electron').ipcRenderer;
ipcRenderer.on('store-data', function (event,store) {
    console.log(store);
});

您需要 ipcMain 模块来实现此...如 API "When used in the main process, it handles asynchronous and synchronous messages sent from a renderer process (web page). Messages sent from a renderer will be emitted to this module."

中所述

API ipcMain 模块的文档: https://electronjs.org/docs/api/ipc-main

要使用 ipcMain,您需要在 webPreferences

上启用 nodeIntegration
win = new BrowserWindow({
    webPreferences: {
        nodeIntegration: true,
    }
})

小心这可能会导致安全问题。

例如:假设我们要将配置 (json) 文件传递​​到网页

(三点 (...) 代表您的代码已经放在文件中,但与此示例无关)

main.js

...

const { readFileSync } = require('fs') // used to read files
const { ipcMain } = require('electron') // used to communicate asynchronously from the main process to renderer processes.
...

// function to read from a json file
function readConfig () {
  const data = readFileSync('./package.json', 'utf8')
  return data
}

...
// this is the event listener that will respond when we will request it in the web page
ipcMain.on('synchronous-message', (event, arg) => {
  console.log(arg)
  event.returnValue = readConfig()
})
...

index.html

...    
<script>
    <!-- import the module -->
    const { ipcRenderer } = require('electron')

    <!-- here we request our message and the event listener we added before, will respond and because it's JSON file we need to parse it -->
    var config = JSON.parse(ipcRenderer.sendSync('synchronous-message', ''))

    <!-- process our data however we want, in this example we print it on the browser console -->
    console.log(config)

     <!-- since we read our package.json file we can echo our electron app name -->
     console.log(config.name)
</script>

要查看浏览器的控制台,您需要从默认的 Electron 菜单或您的代码中打开开发工具。 例如在 createWindow() 函数中

 win.webContents.openDevTools()