场景:在main.js中,用win.loadURL()加载了一个外部网页,网页中存在window.open()或带target="_blank" 的链接,会自动创建一个新的窗口打开,这不符合预期
在main.js中(代码做了简化)
const { app, BrowserWindow } = require('electron')
app.whenReady().then(() => {
const win = new BrowserWindow()
win.loadURL('https://www.baidu.com')
win.webContents.setWindowOpenHandler( details =>{
win.loadURL(details.url)
})
})
官方文档
contents.setWindowOpenHandler(handler)
handler Function<{action: 'deny'} | {action: 'allow', overrideBrowserWindowOptions?: BrowserWindowConstructorOptions}>
-
details Object
-
url string - window.open()传入的 resolved 的URL。 例如,使用 window.open('foo') 打开一个窗口,将产生类似值 https://the-origin/the/current/path/foo。
-
frameName string - window.open() 提供的窗口的名称。
-
features string - window.open() 提供 逗号 分割的窗口特征列表。
-
disposition string - 可以是 default, foreground-tab, background-tab, new-window, save-to-disk or other.
-
referrer Referrer - referrer 将传到新窗口。 可能会也可能不会发送 Referer 头,取决于 referrer 策略。
-
postBody PostBody (可选) - post 数据发送至新窗口,以及设置适当的请求头(headers)。 如果没有 post 数据被发送,值将为 null。 仅当窗口从 form 并设置 target=_blank 时创建,才会被定义。
-
返回 {action: 'deny'} | {action: 'allow', overrideBrowserWindowOptions?: BrowserWindowConstructorOptions} - deny 取消创建新窗口。
allow 将允许新窗口被创建。
指定 overrideBrowserWindowOptions 允许自定义创建的窗口参数。
返回无法识别的值 ,例如 null,undefined,或 一个没有 action 成员的对象, 控制同将输出错误,同时与返回 {action: 'deny'} 效果相同。(这句是解决问题的关键)