问题
I'm writing my first electron app, so please be lenient :)
When the user presses a button on the main Window, there should open a new window which shows some json string. This event gets cought by ipcMain:
ipcMain.on("JSON:ShowPage", function(e, item) {
createJSONWindow(item);
})
This is the function where I create the new window:
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;
});
}
Now to my question, when I have multiple JSONWindow
s open, every single one of them gets the JSON:Display
Message and updates it's content. Shouldn't they work independently from each other? The jsonWin
is always a new BrowserWindow
, isn't it?
Thanks in advance.
回答1:
The problem is this code:
ipcMain.on('JSON_PAGE:Ready', function(event, arg) {
jsonWin.webContents.send('JSON:Display', item);
})
Every time you create a new window, you are having ipcMain
subscribe to the same message. This means that when ipcMain
gets the 'JSON_PAGE:Ready'
message, it calls every single callback it has registered and sends a message to every single window.
The simplest solution in this case is to use the event that's passed to the ipcMain
handler to send the message to the renderer that sent it to main. Second, subscribe a single time outside of createJSONWindow
:
ipcMain.on('JSON_PAGE:Ready', function(event, arg) {
e.sender.send('JSON:Display', item);
});
function createJSONWindow() { ... }
However, is 'JSON:Display'
simply sent when the page has loaded? If so, you can subscribe the window's webContents to the did-finish-load event which fires when the page has loaded.
jsonWin.webContents.on("did-finish-load", () => {
jsonWin.webContents.send(...);
});
来源:https://stackoverflow.com/questions/58975598/how-to-send-messages-to-different-windows-in-electron