yccteam
yccteam

Reputation: 2311

Electron - how to handle in page popups

Inside electron I'm loading an old site.

The code is simple: browserWindow.loadURL('https://myOldSite.com');

This old site opens a popup (e.g. <a target="_blank"...> or even js window.open) when a user clicks a button.

When the popup opens, I see something flashing on screen, but it doesn't stay open. I have 2 questions:

  1. Is there a way to prevent this flash?
  2. Is there a way to control this popup and show it to the user? Or get its URL in some way?

Upvotes: 0

Views: 6665

Answers (2)

pergy
pergy

Reputation: 5531

First of all, it should work as expected. Both window.open and <a target="_blank" ... > opens a new electron BrowserWindow.

However, you can manipulate the window opening process in main process by 'new-window' event:

myBrowserWindow.webContents.on('new-window', (event, url) => {
  event.preventDefault()
  const win = new BrowserWindow({show: false})
  win.once('ready-to-show', () => win.show())
  win.loadURL(url)
  event.newGuest = win
})

This example gracefully shows the new window but you can achieve a lot more with available callback arguments

Upvotes: 2

hamstu
hamstu

Reputation: 1644

One solution would be to use the preload option when creating your BrowserWindow.

From the documentation:

preload String (optional) - Specifies a script that will be loaded before other scripts run in the page. This script will always have access to node APIs no matter whether node integration is turned on or off. The value should be the absolute file path to the script. When node integration is turned off, the preload script can reintroduce Node global symbols back to the global scope. See example here.

Your preload script could search the page for the links you mentioned and change their behavior. (I.e., send an event to your main process instead to do whatever action you like; open a window, etc.)

Upvotes: 1

Related Questions