【问题标题】:How to send messages to different windows in electron?如何将消息发送到电子中的不同窗口?
【发布时间】:2020-03-17 10:12:38
【问题描述】:

我正在编写我的第一个电子应用程序,所以请宽容:)

当用户按下主窗口上的按钮时,应该会打开一个显示一些 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;
    });
}

现在我的问题是,当我打开多个JSONWindows 时,每个人都会收到JSON:Display 消息并更新其内容。他们不应该彼此独立工作吗? jsonWin 总是一个新的BrowserWindow,不是吗?

提前致谢。

【问题讨论】:

    标签: javascript npm electron


    【解决方案1】:

    问题是这段代码:

    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 事件。

    jsonWin.webContents.on("did-finish-load", () => {
        jsonWin.webContents.send(...);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多