electron 阻止window.open()或带target=“_blank“ 的链接在新窗口打开

场景:在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'} 效果相同。(这句是解决问题的关键)

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值