Electron: How to refocus/restore a minimised DevTools window

Viewed 395

I've created a global shortcut where Ctrl+Shift+I opens a detached DevTools window. However, when the DevTools window is minimised, pressing Ctrl+Shift+I does not do anything.

I want to be able to restore/unminimise the minimised DevTools window by using the Ctrl+Shift+I shortcut. The .focus method usually works for things like this but doesn't in this case. I've tried using 'undocked' mode for the window too.

The code I have to implement the current behaviour is this:

if (focussedWindow.webContents.isDevToolsOpened()) {
      if (focussedWindow.webContents.devToolsWebContents !== null) {                            
              focussedWindow.webContents.devToolsWebContents.focus();
       }
}

I should also add that the DevTools window does refocus if it is behind other windows, just not when minimised.

I'm using Electron 9.3.0 on Windows 10 Pro.

1 Answers

The Situation

On Linux, BrowserWindow.webContents.devToolsWebContents.focus() restores the minimized detached DevTools window – as desired.

On Windows, this does not work (tested with Electron 9.3.0 and 10.1.1 on Win 7). The minimized detached DevTools window stays minimized.

Workaround

After trying many workarounds that all did not work on Windows, I found the following trick: make a new BrowserWindow for the DevTools to occupy. With this reference, you can now simply call BrowserWindow.restore().

const {app, BrowserWindow} = require("electron");
const url = require("url");
const path = require("path");

let mainWindow, newDevToolsWindow;

app.on("ready", function() {
    mainWindow = new BrowserWindow();

    mainWindow.loadURL(url.format({
        pathname: path.join(__dirname, "index.html"),
        protocol: "file:",
        slashes: true
    }));

    console.log("create new window for devtools")
    newDevToolsWindow = new BrowserWindow();
    mainWindow.webContents.setDevToolsWebContents(newDevToolsWindow.webContents);
    mainWindow.webContents.openDevTools({mode: "detach"});

    // Simulate OP's keypress
    setInterval(() => {
        console.log("restore the new window")
        newDevToolsWindow.restore();
    }, 4000);

});

Notes:

  • The workaround was tested with Electron 9.3.0 and 10.1.1 on Win 7.
  • You may need to adapt the BrowserWindow a little, if you want to replicate the standard DevTools window behavior in detach mode.
  • Also note that isDevToolsOpened will return false, so you need to adapt your checks as well.
Related