HesamSe
HesamSe

Reputation: 355

Electron ApplicationMenu only works for last window when you have multiple windows

I'm tying to have Multiple windows in my Electron app and each window should have its own applicationMenu. But when I open a new window, the functionalities in application menu such as reload and openDevTools only works for last window that just opened. Why this is happening? Code example:

app.on('ready',() => {
  createWindow();
});

ipcMain.on('open-new-window',() => {
  createWindow();
});


function createWindow() {
  const window = new BrowserWindow({
    width:900,
    height:700,
    webPreferences: {
      nodeIntegration: true
    }
  });
  window.loadUrl('index.html');
  const menu = Menu.buildFromTemplate([{
    label: "dev",
    submenu: [{
      label: "Refresh HTML",
      click: () => {
        window.reload();
      }
    }]
  }]);
  Menu.setApplicationMenu(menu);
}

When i open a new window from ipcMain, the reload() function only works in last opened window. Whether i click "Refresh HTML" in the first window or the second.

Upvotes: 2

Views: 204

Answers (1)

pergy
pergy

Reputation: 5521

You have only one piece of application menu, which (from docs)

will be set as each window's top menu

So, when you overwrite it, this is the expected behavior. Let's say

  1. You create window #1. window variable will refer to #1, thus your application menu will reload that.
  2. You create window #2. window refer to #2 and you overwrite application menu to reload #2 upon click
  3. Clicking on #1's menu will reload #2 anyway

To resolve this, you can reload the current window with BrowserWindow.getFocusedWindow(), this way your MenuItem's function won't depend on the reference of window.

Try

click: () => {
  BrowserWindow.getFocusedWindow().reload();
}

Upvotes: 1

Related Questions