我正在编写我的第一个电子应用程序,所以请宽容:)
当用户按下主窗口上的按钮时,应该打开一个新窗口,其中显示一些 json 字符串。
该事件由 ipcMain 处理:
ipcMain.on("JSON:ShowPage", function(e, item) {
createJSONWindow(item);
})
这是我创建新窗口的函数:
function createJSONWindow(item) {
let jsonWin = new BrowserWindow({
width: 600,
height: 800,
center: true,
resizable: true,
webPreferences:{
nodeIntegration: true,
show: false
}
});
jsonWin.loadFile("jsonView.html");
ipcMain.on('JSON_PAGE:Ready', function(event, arg) {
jsonWin.webContents.send('JSON:Display', item);
})
jsonWin.once('ready-to-show',()=>{
jsonWin.show()
});
jsonWin.on('closed',()=>{
jsonWin = null;
});
}
现在回答我的问题,当我有多个JSONWindow
打开,他们每个人都得到JSON:Display
消息并更新其内容。他们不应该彼此独立工作吗?这jsonWin
永远是新的BrowserWindow
,不是吗?
提前致谢。
问题是这段代码:
ipcMain.on('JSON_PAGE:Ready', function(event, arg) {
jsonWin.webContents.send('JSON:Display', item);
})
每次你创建一个新窗口时,你都会有ipcMain
订阅同一条消息。这意味着当ipcMain
得到'JSON_PAGE:Ready'
消息,它调用它注册的每个回调并向每个窗口发送一条消息。
在这种情况下,最简单的解决方案是使用传递给ipcMain
处理程序将消息发送到将其发送到 main 的渲染器。二、单次订阅时间之外createJSONWindow
:
ipcMain.on('JSON_PAGE:Ready', function(event, arg) {
e.sender.send('JSON:Display', item);
});
function createJSONWindow() { ... }
然而,是'JSON:Display'
只是在页面加载时发送?如果是这样,您可以将窗口的 webContents 订阅到did-finish-load https://electronjs.org/docs/api/web-contents#event-did-finish-load页面加载时触发的事件。
jsonWin.webContents.on("did-finish-load", () => {
jsonWin.webContents.send(...);
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)