You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Electron中新浏览器窗口配置选项不生效问题求助

解决Electron new-window事件窗口配置不生效的问题

核心问题分析

你的代码里窗口配置不生效主要有两个原因:

  • new-window事件传入的options对象可能已包含Electron默认的窗口尺寸属性,直接修改后可能未正确覆盖默认值;且你只设置了height但未指定width,窗口会沿用默认宽度,导致看起来高度配置未生效;
  • 主窗口关闭后win变量会被设为null,此时创建模态窗口会因parent为null导致模态等配置失效。

修正后的代码

/* main.js v2 */
const { app, BrowserWindow } = require('electron')
const path = require('path')
const url = require('url')

let mainWindow // 重命名变量避免歧义

function createWindow () {
  mainWindow = new BrowserWindow({ width: 800, height: 600 })

  mainWindow.loadURL(url.format({
    pathname: 'localhost:3500/session',
    protocol: 'http:',
    slashes: true
  }))

  mainWindow.on('closed', () => {
    mainWindow = null
  })
}

app.on('ready', createWindow)

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (mainWindow === null) {
    createWindow()
  }
})

// 合并重复的监听逻辑,精简代码
app.on('web-contents-created', (event, contents) => {
  contents.on('will-navigate', (event, navigationUrl) => {
    const allWindows = BrowserWindow.getAllWindows()
    for (const win of allWindows) {
      if (win.webContents.getURL() === navigationUrl) {
        win.close()
        return
      }
    }
  })
})

app.on('new-window', (event, url, frameName, disposition, options, additionalFeatures) => {
  if (frameName === 'modal') {
    event.preventDefault()
    // 先检查主窗口是否存在,避免报错
    if (!mainWindow) return
    // 使用对象展开语法合并配置,确保自定义配置优先级更高
    const modalWindow = new BrowserWindow({
      ...options,
      modal: true,
      parent: mainWindow,
      width: 400, // 必须明确指定宽度
      height: 250,
      resizable: false // 可选:禁止窗口调整大小,强化模态窗口特性
    })
    event.newGuest = modalWindow
    modalWindow.loadURL(url)
  }
})

关键修正点

  • 明确指定完整窗口尺寸:同时设置width和height,避免Electron使用默认值导致配置看起来未生效;
  • 用对象展开语法合并配置:{ ...options, ...自定义配置 }能确保自定义属性覆盖默认选项,比Object.assign更直观;
  • 增加主窗口存在性校验:防止主窗口关闭后创建模态窗口时出现parent为null的错误;
  • 精简重复代码:移除主窗口内重复的web-contents-created监听,统一在app层面处理。

内容的提问来源于stack exchange,提问作者LHHHH

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 07:15:34