Electron: close browser tab opened via shell.openExternal

168 Views Asked by At

I'm setting up auth in my Electron app using ionic-appauth. I am trying to make the OS open the default browser to process the auth call and show the login page.

I implemented this using a custom browser that gets injected into my Ionic Angular app when it detects the Electron runtime:

import { Browser } from 'ionic-appauth';

export class ElectronBrowser extends Browser {
  private openedWindow?: Window;

  showWindow(url: string): undefined {
    this.openedWindow = window.open(url, '_self') ?? undefined;
    return;
  }

  closeWindow(): void {
    if (this.openedWindow) {
      this.openedWindow.close();
      this.openedWindow = undefined;
    }
  }
}

As well as using this setWindowOpenHandler for the main Electron window:

mainWindow.webContents.setWindowOpenHandler((details) => {
  shell.openExternal(details.url);
  return { action: 'deny' };
});

I mainly wanted to do this to reuse the session the user might have in the browser (avoids having to re authenticate in the Electron app) and to avoid rendering the login page (Azure AD) in an Electron page, which requires me to update the Electron's app CSP to be able to render the page.

As shown above I am using shell.openExternal for this setup. This works great except that I can't seem to get a handle on the opened window in the ElectronBrowser (from window.open) and so after the callback completes and the user is logged in in the Electron app, the browser tab remains open.

Is there any way I can close a browser tab opened through shell.openExternal or is my setup with trying to reuse the default browser and session badly conceived or just plain wrong?

0

There are 0 best solutions below