我正在学习Electron并使用多个窗口和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();
});
Run Code Online (Sandbox Code Playgroud)
在我的主窗口的脚本中,我在商店列表中的click事件中有以下内容:
$.getJSON("http://localhost:8080/stores/" + item.id).done(function(store) {
ipc.send('show-store-edit', store);
});
Run Code Online (Sandbox Code Playgroud)
在控制台上,我从我的服务器打印商店数据.我不清楚的是如何将数据放入视图中storeWindow:store.html
.我甚至不确定我是否正确处理事件序列,但它们将是:
要么
在后者中,我不确定如何获得从storeWindow's
脚本中获取存储所需的ID .
Mic*_*nov 53
要将事件发送到特定窗口,您可以使用webContents.send(EVENT_NAME, ARGS)
(请参阅文档).webContents
是窗口实例的属性:
// main process
storeWindow.webContents.send('store-data', store);
Run Code Online (Sandbox Code Playgroud)
要侦听正在发送的此事件,您需要在窗口进程(渲染器)中使用侦听器:
// renderer process
var ipcRenderer = require('electron').ipcRenderer;
ipcRenderer.on('store-data', function (event,store) {
console.log(store);
});
Run Code Online (Sandbox Code Playgroud)
use*_*607 10
您需要 ipcMain 模块来实现这一点......正如 API 中所述“当在主进程中使用时,它处理从渲染器进程(网页)发送的异步和同步消息。从渲染器发送的消息将被发送到这个模块。”
ipcMain 模块的 API 文档: https ://electronjs.org/docs/api/ipc-main
要使用 ipcMain,您需要在webPreferences 上启用nodeIntegration
win = new BrowserWindow({
webPreferences: {
nodeIntegration: true,
}
})
Run Code Online (Sandbox Code Playgroud)
小心这可能会导致安全问题。
例如:假设我们要向网页传递一个配置(json)文件
(三个点 (...) 表示您的代码已放置在文件中,但与此示例无关)
主文件
...
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()
})
...
Run Code Online (Sandbox Code Playgroud)
索引.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>
Run Code Online (Sandbox Code Playgroud)
要查看浏览器的控制台,您需要从默认的 Electron 菜单或您的代码中打开开发工具。 例如在 createWindow() 函数中
win.webContents.openDevTools()
Run Code Online (Sandbox Code Playgroud)