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

How to load a html file into the current window in Electron?

1个答案

1

In Electron, loading an HTML file into the current window is typically achieved by using the loadFile method of the BrowserWindow class. BrowserWindow is a class in Electron used for controlling and manipulating application windows. I will now outline the steps and provide a specific example.

Steps

  1. Create a new BrowserWindow instance: First, create a window instance using Electron's BrowserWindow class.

  2. Load the HTML file: Use the loadFile method to load a local HTML file into this window.

Example

Assuming you already have the basic structure of an Electron application, here is an example of how to load an index.html file into the window:

javascript
// Import BrowserWindow from electron const { app, BrowserWindow } = require('electron') // Create an async function to handle window creation and file loading function createWindow() { // Create a new window instance const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) // Load the index.html file from the current directory win.loadFile('index.html') } // When the Electron app is ready to create browser windows, this method is called app.whenReady().then(createWindow) // Quit the app when all windows are closed (Windows & Linux) app.on('window-all-closed', () => { if (process.platform !== 'darwin') app.quit() }) // Create a new window when the app is activated (e.g., clicking the app icon from the Dock) app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) { createWindow() } })

In this example, the index.html file is loaded into a window that is 800 pixels wide and 600 pixels high. The nodeIntegration option in webPreferences is set to true, enabling the use of Node.js APIs within this window.

This approach is well-suited for loading the application's user interface and can be combined with other Electron APIs for more complex operations and interactions.

2024年6月29日 12:07 回复

你的答案