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

How can I access the BrowserWindow JavaScript global from the main process in Electron?

1个答案

1

In Electron, the main process manages the application lifecycle, including creating and managing browser windows. BrowserWindow is a class within the electron module for creating and controlling browser windows. To access BrowserWindow from the main process, you must create and manage the window using the Electron module in the main process's JavaScript file.

Here is a basic example demonstrating how to create a BrowserWindow in Electron's main process:

  1. Importing Electron and Creating BrowserWindow:
javascript
const { app, BrowserWindow } = require('electron'); function createWindow () { // Create a new browser window let win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }); // Load the application's index.html win.loadFile('index.html'); } app.whenReady().then(createWindow);

In this example, app and BrowserWindow are imported from the electron module. The app object handles application lifecycle events, such as startup and shutdown. A createWindow function is defined to instantiate a new BrowserWindow object. Within the BrowserWindow constructor, you can configure window properties like dimensions and web preferences.

  1. Listening to Application Events: Electron's app module provides events such as whenReady and before-quit, which are used to manage window creation and application termination.

  2. Loading HTML Files: Use the win.loadFile method to load an HTML file into the created window. This file serves as the application's user interface.

This approach enables successful creation and access of BrowserWindow from the main process. For dynamic management or access across multiple locations or event triggers, store the win variable in a global scope or implement state management for access and control.

2024年6月29日 12:07 回复

你的答案