如何获取调用事件的BrowserWindow实例?

时间:2019-03-28 23:47:18

标签: electron

示例

您已打开多个BrowserWindows并将其存储在BrowserWindows数组中,您想知道哪个窗口称为close事件,以便可以从数组中删除该特定的BrowserWindow。

window.on('close', () => {
   // Get the instance of the window that called this event
})

如何?

2 个答案:

答案 0 :(得分:0)

BrowserWindowEventEmitter;这样,窗口的实例方法on在回调函数中返回一个event参数,您可以使用event.sender属性从中访问窗口的实例。

window.on ('close', (event) => {
    // Use event.sender to get the instance of the window that called this event
    console.log (event.sender instanceof BrowserWindow); // -> true
    console.log (event.sender === window); // -> true
});

答案 1 :(得分:0)

由于event.sender类型为WebContents,因此您无法将其与BrowserWindow进行比较,只有将event.senderBrowserWindow.webContents属性进行比较,但我猜测不会提供唯一的标识。一种解决方法是将event.sender.idwindow.id

进行比较
window.on ('close', (event) => {
    // Use event.sender to get the instance of the window that called this event
    console.log (event.sender.id === window.id); // -> true
});