Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Electron Creating and Managing Windows

Electron Creating and Managing Windows

In Electron, a window is the core carrier for interaction between the app and the user.

All visual interfaces run in Renderer Process , while the creation and control of these windows is handled by Main Process is responsible.


Create and manage windows

Electron uses the BrowserWindow class to create windows.

Define a new window in the main process as follows:

Example

const

{

BrowserWindow

}

=

require

(

'electron'

)

let mainWindow

=

new

BrowserWindow

(

{

  width

:

1200

,

  height

:

800

,

  show

:

false

,

// Show it only after the page is ready

  webPreferences

:

{

    preload

:

path.

join

(

__dirname

,

'preload.js'

)

,

 

}

,

}

)

BrowserWindow configuration options

Window size, position, and state
Window state can be controlled via the API:

mainWindow.maximize()   // 最大化

mainWindow.minimize()   // 最小化

mainWindow.restore()    // 还原

mainWindow.setBounds({ x: 100, y: 100, width: 800, height: 600 }) // 调整位置和大小

You can also listen for window changes:



mainWindow.on('resize', () => console.log('窗口尺寸变化'))

mainWindow.on('move', () => console.log('窗口移动'))

Frameless windows and custom title bars
Settings frame: false After that, you can customize the title bar area and simulate dragging with CSS and JS:



.titlebar {

  -webkit-app-region: drag;

}

Note that non-draggable areas (such as buttons) should add:

.titlebar {

  -webkit-app-region: drag;

}

Window event listening

mainWindow.on('close', (e) => {

  e.preventDefault()

  mainWindow.hide()

})

Common events include:


Loading page content

Electron windows can load local HTML files or remote websites.

Load a local HTML file

mainWindow.loadFile('index.html')

Load a remote URL

mainWindow.loadURL('https://example.com')

Using front-end frameworks
If you use modern frameworks such as Vue, React, or Angular, you can load the built static files into the window:

mainWindow.loadFile(path.join(__dirname, 'dist/index.html'))

Or load a local service in development mode:

mainWindow.loadURL('http://localhost:5173')


Communication between windows

In multi-window apps, you may need to pass data or control behavior between windows.

Parent-child window relationship
You can specify when creating a new window parent:



let child = new BrowserWindow({

  parent: mainWindow,

  modal: true, // 模态窗口

  width: 400,

  height: 300,

})

When the parent window closes, the child window also closes automatically.

Multi-window data sharing
Data can be passed between different renderer processes via the main process as an intermediary, or use global objects or ipcMain / ipcRenderer.

Window message passing
The main process can directly operate the target window:

child.webContents.send('update-data', someData)

Receive in the child window:

const { ipcRenderer } = require('electron')

ipcRenderer.on('update-data', (event, data) => {

  console.log(data)

})


UI optimization

Splash screen
When the main window loads slowly, you can first show a lightweight startup window:

const splash = new BrowserWindow({ width: 400, height: 300, frame: false })

splash.loadFile('splash.html')



mainWindow.once('ready-to-show', () => {

  splash.close()

  mainWindow.show()

})

Window display optimization
To prevent white-screen flicker, common techniques include:

Techniques to prevent flicker


Multi-window Electron app (including splash page, main UI, and child windows)

** Directory structure**



my-electron-app/

├── package.json

├── main.js             # 主进程入口

├── preload.js          # 预加载脚本

├── splash.html         # 启动画面

├── index.html          # 主窗口页面

├── child.html          # 子窗口页面

└── renderer.js         # 渲染进程逻辑

main.js (main process)

Example

const

{

app

,

BrowserWindow

,

ipcMain

}

=

require

(

'electron'

)

const

path

=

require

(

'path'

)

let mainWindow

,

splash

,

childWindow

function

createSplash

(

)

{

  splash

=

new

BrowserWindow

(

{

    width

:

400

,

    height

:

300

,

    frame

:

false

,

    transparent

:

true

,

    alwaysOnTop

:

true

,

 

}

)

  splash.

loadFile

(

'splash.html'

)

}

function

createMainWindow

(

)

{

  mainWindow

=

new

BrowserWindow

(

{

    width

:

1200

,

    height

:

800

,

    show

:

false

,

    webPreferences

:

{

      preload

:

path.

join

(

__dirname

,

'preload.js'

)

,

   

}

,

 

}

)

  mainWindow.

loadFile

(

'index.html'

)

 

// Show after the page finishes loading

  mainWindow.

once

(

'ready-to-show'

,

(

)

=>

{

   

if

(

splash

)

splash.

close

(

)

    mainWindow.

show

(

)

 

}

)

  mainWindow.

on

(

'closed'

,

(

)

=>

(

mainWindow

=

null

)

)

}

function

createChildWindow

(

)

{

  childWindow

=

new

BrowserWindow

(

{

    parent

:

mainWindow

,

    modal

:

true

,

    width

:

400

,

    height

:

300

,

    webPreferences

:

{

      preload

:

path.

join

(

__dirname

,

'preload.js'

)

,

   

}

,

 

}

)

  childWindow.

loadFile

(

'child.html'

)

}

// Inter-process communication

ipcMain.

on

(

'open-child'

,

(

)

=>

{

 

if

(

!

childWindow

)

createChildWindow

(

)

}

)

ipcMain.

handle

(

'get-app-info'

,

(

)

=>

{

 

return

{

    name

:

app.

getName

(

)

,

    version

:

app.

getVersion

(

)

,

 

}

}

)

app.

on

(

'ready'

,

(

)

=>

{

  createSplash

(

)

  setTimeout

(

(

)

=>

createMainWindow

(

)

,

1500

)

}

)

app.

on

(

'window-all-closed'

,

(

)

=>

{

 

if

(

process.

platform

!==

'darwin'

)

app.

quit

(

)

}

)

preload.

js

(preload script)

const

{

contextBridge

,

ipcRenderer

}

=

require

(

'electron'

)

contextBridge.

exposeInMainWorld

(

'electronAPI'

,

{

  openChild

:

(

)

=>

ipcRenderer.

send

(

'open-child'

)

,

  getAppInfo

:

(

)

=>

ipcRenderer.

invoke

(

'get-app-info'

)

,

}

)

** index.html (main window)**

Example

DOCTYPE html

<

html lang

=

"zh"

<

head

<

meta charset

=

"UTF-8"

/>

 

<

title

Main window

title

 

<

style

body

{

font

family

:

sans

serif

;

text

align

:

center

;

margin

top

:

100px

;

}

    button

{

padding

:

10px 20px

;

font

size

:

16px

;

cursor

:

pointer

;

}

 

style

head

<

body

<

h1

Welcome to the Electron app

h1

 

<

p id

=

"info"

p

 

<

button id

=

"open"

Open child window

button

 

<

script src

=

"renderer.js"

script

body

html

** child.html (child window)**

Example

 

 

<p>Child window</p>

 

 

This is a child window

 

Can receive instructions from the main window

** splash.html (splash screen)**

Example

 

 

<p>Loading...</p>

 

 

App is starting, please wait...

** renderer.js (rendering logic)**

Example

const

info

=

document.

getElementById

(

'info'

)

const

btn

=

document.

getElementById

(

'open'

)

// Display app information

window.

electronAPI

.

getAppInfo

(

)

.

then

(

(

appInfo

)

=>

{

  info.

textContent

=

`App name: $

{

appInfo.

name

}

| Version: $

{

appInfo.

version

}

`

}

)

// Open child window

btn.

addEventListener

(

'click'

,

(

)

=>

{

  window.

electronAPI

.

openChild

(

)

}

)

The flow after running is as follows:

  1. Show at startup Splash screen (splash.html).
  2. After loading completes, automatically close the splash page and show Main window.
  3. The main window can open via a button child window, demonstrating IPC communication.
  4. The main window uses Preload safely exposes the API, preventing direct access to Node.js.
  5. All windows use Event Listening, delayed display and other optimization strategies to avoid blank screens and flicker.