javascriptreactjselectronwindow-objectelectron-react

How to know if an external URL is loaded successfully from the main process when using window.open() from the renderer process


Is it possible to identify whether an external URL is loaded successfully or not from the main process, when window.open("http://example.com") is called from the renderer process?

Something like...

mainWindow.webContents.on('did-url-load', () => {
  // Do something
});

mainWindow.webContents.on('did-url-loading-failed', () => {
  // Do something
});

Solution

  • I worked this out by creating a new BrowserWindow object to load the URL sent from the renderer process and then used the loadURL promise to identify whether the external URL is loaded successfully or not. I am not sure if anything simpler than this can be done.

    mainWindow.webContents.setWindowOpenHandler(({ url }) => {
      const urlWindow = new BrowserWindow({
        show: false,
      });
      urlWindow.maximize();
      urlWindow
        .loadURL(url)
        .then(() => {
          // Handle URL loaded successfully
        })
        .catch(() => {
          // Handle URL loading failed, like throw some error using dialog.showMessageBox
        });
      return {
        action: 'deny',
      };
    });