simonw/datasette-app

Debug -> Open Chromium DevTools error if no windows open

simonw opened this issue · 3 comments

That menu option expects there to be a focused browser window that it can open into:

datasette-app/main.js

Lines 955 to 960 in 97dd4f6

{
label: "Open Chromium DevTools",
click() {
BrowserWindow.getFocusedWindow().webContents.openDevTools();
},
},

If no windows are open it shows this error:

New_Issue_·_simonw_datasette-app

Ideally the menu option would be disabled if there were no windows open - if there's at least one open then it works, opening in either the currently focused window or the first in the list of windows.

I can disable the menu item by calculating if it should be enabled in buildMenu() and then calling that in the window-all-closed event.

After setting the enabled state of that action to depend on if there were any browser windows open, the tricky thing was figuring out an event I could listen to that could be used to re-calculate that enabled state when going from 0 browser windows to 1.

To test this: close all windows, the item should become greyed out - then hit Command+N to open a new window, the menu item should become enabled again.

I tried using the browser-window-created event but at the point that event fires the window hasn't been created, so BrowserWindow.getAllWindows().length still returns 0.

The fix was a setTimeout():

app.on("browser-window-created", function () {
  // To re-enable DevTools menu item when a window opens
  // Needs a slight delay so that the code can tell that a
  // window has been opened an the DevTools menu item should
  // be enabled.
  if (datasette) {
    setTimeout(() => {
      Menu.setApplicationMenu(Menu.buildFromTemplate(buildMenu()));
    }, 300);
  }
});