我正在尝试将数据从 Electron 应用程序的主窗口传递给
新窗口,由于用户操作而打开,但是我似乎无法获得
进程间通信工作。
以下是说明我的问题的最小示例。
为了简洁起见,我将所有的javascript代码都包含在其中,
呈现过程进入html页面。
index.html的正文:
<body>
<h1>Passing data to new window</h1>
<input id="testBtn" type="button" value="Testclick"></input>
<script>
const { ipcRenderer } = require('electron')
testBtn.addEventListener('click', () => {
ipcRenderer.send('asynchronous-message', '')
console.log("sent asynchronously")
});
</script>
</body>
主流程index.js的相关部分:const {app, BrowserWindow, ipcMain} = require('electron')
function createWindow () {
window = new BrowserWindow({
webPreferences: {
nodeIntegration: true
},
width: 800, height: 600
})
window.loadFile('index.html')
window.openDevTools();
}
app.on('ready', createWindow);
const { readFileSync } = require('fs')
//sample data: read project package-file
function readConfig () {
const data = readFileSync('./package.json', 'utf8')
return data
}
ipcMain.on('asynchronous-message', (event, arg) => {
console.log("asynchronous-message triggered")
console.log(arg)
subwindow = new BrowserWindow({
webPreferences: {
nodeIntegration: true
},
width: 800, height: 600
})
console.log("after creating subwindow...")
subwindow.loadFile('sub.html')
subwindow.webContents.send('filecontents-msg', readConfig());
subwindow.openDevTools();
})
sub.html的相关部分: <body>
<h1>SUBWINDOW</h1>
<p id="fileContents"></p>
<script>
console.log("executing script of sub.html")
const { ipcRenderer } = require('electron')
ipcRenderer.on('filecontents-msg', (event, arg) => {
console.log("processing message filecontents-msg")
document.getElementById("fileContents").innerHTML = arg;
})
</script>
</body>
sub.html中的脚本已执行,但显然从未收到'filecontents-msg'(即传递给
ipcRenderer.on
的函数的函数主体永远不会执行,当我更换管线时都没有
subwindow.webContents.send('filecontents-msg', readConfig());
在index.js中event.reply('filecontents-msg', readConfig())
有人可以提供一个工作示例,说明如何将数据从主流程传递到新窗口,由另一个窗口中的某个用户事件触发?
最佳答案
因此,显然问题出在新窗口就绪之前发送的消息。我发现修改后数据已正确加载到新窗口中
在index.js中加载和发送命令,如下所示:
subwindow.loadFile('sub.html');
subwindow.webContents.on('did-finish-load', () => {
subwindow.webContents.send('filecontents-msg', readConfig())
})
关于javascript - 根据 Electron 主过程中生成的数据创建新窗口的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65764807/