Electron: Returning focus

It was a giant faff to get an electron app to return focus to the previous window - here's how I do it

Returning window focus back to where it was is pretty painful and I want to save you, and future me, from that pain.

Here's how to do it.

Mac

For Mac we simply need to hide all the windows, then re-show the mainWindow but without giving it focus.

app.hide(); // Hides the app + all windows
mainWindow.showInactive(); // Return the main window to view, but without focus

Windows

The showInactive method used for Mac doesn't return focus on Windows, so we instead create a dummy window, then close it, so focus is returned correctly.

// Blur the main window
// Create a dummy window off-screen, then close that, returning focus

mainWindow.blur();
mainWindow.setOpacity(0);

const dummyTransparentWindow = new BrowserWindow({
    width: 1,
    height: 1,
    x: -100,
    y: -100,
    transparent: true,
    frame: false,
  });

dummyTransparentWindow.close();
dummyTransparentWindow.on('closed', () => {
    mainWindow.setOpacity(1);
    mainWindow.setAlwaysOnTop(true, 'screen-saver');
});

Combined

Let's combine them into a convenient ol' function

function returnFocus()
{
    // Don't attempt to return focus if the main window doesn't exist
    if (mainWindow === null) {
        return;
    }

    if (process.platform === 'darwin') {
        app.hide();
        mainWindow.showInactive();
        return;
    }

    if (process.platform === 'win32') {
        mainWindow.blur();
        mainWindow.setOpacity(0);

        const dummyTransparentWindow = new BrowserWindow({
            width: 1,
            height: 1,
            x: -100,
            y: -100,
            transparent: true,
            frame: false,
          });

        dummyTransparentWindow.close();
        dummyTransparentWindow.on('closed', () => {
            mainWindow.setOpacity(1);
            mainWindow.setAlwaysOnTop(true, 'screen-saver');
        });
    }
}

Wanna know when new stuff happens?

Sign up to the haphazard newsletter

Unsubscribe whenever you fancy.