首页 > 解决方案 > Electron, Closing "sub-window" from main window

问题描述

I have a main.js file and a add.js, when I click on a button that's in the menu of main.js the second file is called like this:

const mainMenuTemplate = [
 {
  label: 'File',
  submenu: [
      {   
          label: 'Add',
          click(){  //Calling add.js and the function createAddWindow()
                    let add = require( __dirname + '/add.js'); add.createAddWindow(); }   
       }
   ]
 }
]

(This is a simplified version of the actual menu, but the rest is not important)

Now, in add.js I call a html where I use an input, this input is send to main.js like this

<script>
    const electron = require('electron');
    const {ipcRenderer} = electron;

    const form = document.querySelector('form');
    form.addEventListener('submit', submitForm);

    function submitForm(event){
        event.preventDefault();
        const item = document.querySelector('#item').value;
        ipcRenderer.send('item:add',item);
    }

</script>

The problem is that when I "hear" that event in main.js I would like to close the 'add' window but I can't do it like this

ipcMain.on('item:add',function(event, item){
  console.log(item);
  mainWindow.webContents.send('item:add',item);
  add.close();
});

Because of course, add is not defined here. How can I do this?.

I know that I can merge both files into one, but is that a better practice and I'm doing it wrong?

Thanks in advance. I know is quite a long question but I just want to make everything as clear as possible.

标签: node.jselectron

解决方案


这里有几个想法

1) 跟踪主进程中新添加的窗口。

const ADD_WINDOW_ID = 'ADD_WINDOW'
const windows = {}

// make the window

windows[ADD_WINDOW_ID] = new BrowserWindow() // ...

close:add主进程的 IPC 事件中,关闭添加窗口:

if (windows[ADD_WINDOW_ID]) {
    windows[ADD_WINDOW_ID].close()
}

2) 使用webContentsapi 获取此电子应用程序的所有网页内容

这不是一个完整的解决方案,也许调查

每个窗口都有一个唯一标识的 webContents,从添加窗口中,查找当前 web 内容的 id,并将其传递给 IPC 回调:

    // add window
    import { remote } from 'electron'
    const { id } = remote.getCurrentWebContents()

在主进程中

import { webContents } from 'electron'
// on the IPC callback, identify which web contents
const allWebContents = webContents.getAllWebContents()
// todo: find the web contents with the right id, close the window

推荐阅读