乐闻世界logo
搜索文章和话题

How to create a modal window and load HTML from render process in Electron?

1个答案

1

In Electron, creating a modal window and loading HTML from the render process primarily involves the following steps:

1. Creating the Window in the Main Process

First, in your main process file (typically main.js or index.js), you need to use the BrowserWindow class to create a new window. Here, you can set the window as modal by setting the modal property to true and specifying the parent window.

javascript
const { app, BrowserWindow } = require('electron'); function createWindow () { // Create parent window let parentWin = new BrowserWindow({ width: 800, height: 600 }); // Create modal window let modalWin = new BrowserWindow({ width: 400, height: 300, modal: true, parent: parentWin, show: false // Initially not shown, displayed after content loads }); // Load modal window's HTML modalWin.loadFile('modal.html'); modalWin.once('ready-to-show', () => { modalWin.show(); }); parentWin.on('closed', () => { modalWin = null; }); } app.whenReady().then(createWindow);

In the above code, the modal window loads a local HTML file modal.html using the loadFile method. You can include all necessary styles, scripts, and content in this HTML file.

The modal window does not display immediately upon loading content; instead, it displays after the content has loaded using the ready-to-show event. This helps provide a smoother user experience and avoids displaying a blank window.

4. Managing Window Closure

When the parent window is closed, ensure that the modal window is properly closed and cleaned up. In the above example, when the parent window triggers the closed event, the modal window is set to null.

Example: modal.html

Assume your modal.html file may look like this:

html
<!DOCTYPE html> <html> <head> <title>Modal Window</title> </head> <body> <h1>Welcome to the Modal Window</h1> <p>Here is some important information.</p> </body> </html>

This approach ensures that you can create modal windows and load custom HTML content from the render process while maintaining a good user experience and application structure management.

2024年6月29日 12:07 回复

你的答案