|
electron实现主程序中生成一个电脑右下脚弹出窗口,窗口使用browerwindow创建子窗口,并3秒后自动关闭
在 Electron 中,你可以在主程序中创建一个 `BrowserWindow` 窗口,并在这个窗口中显示一个子窗口(也可以称为弹出窗口),然后设置它在 3 秒后自动关闭。以下是实现这一功能的示例代码:
### 1. 在 `main.js` 中创建主窗口和子窗口
- const { app, BrowserWindow } = require('electron');
- const path = require('path');
- function createMainWindow() {
- // 创建主窗口
- const mainWin = new BrowserWindow({
- width: 800,
- height: 600,
- webPreferences: {
- contextIsolation: true,
- preload: path.join(__dirname, 'preload.js') // 使用 preload.js 进行安全通信
- }
- });
- // 加载主窗口的 HTML 文件
- mainWin.loadFile('index.html');
- // 创建子窗口
- const childWin = new BrowserWindow({
- width: 300,
- height: 200,
- x: mainWin.getBounds().x + mainWin.getBounds().width - 310, // 右下角位置
- y: mainWin.getBounds().y + mainWin.getBounds().height - 210,
- alwaysOnTop: true, // 窗口总在最上层
- webPreferences: {
- contextIsolation: true,
- preload: path.join(__dirname, 'preload.js') // 使用 preload.js 进行安全通信
- }
- });
- // 加载子窗口的 HTML 文件
- childWin.loadFile('notification.html');
- // 3秒后自动关闭子窗口
- setTimeout(() => {
- childWin.close(); // 关闭子窗口
- }, 3000);
- }
- // 当应用准备好时创建主窗口
- app.whenReady().then(createMainWindow);
- // 处理关闭事件
- app.on('window-all-closed', () => {
- if (process.platform !== 'darwin') {
- app.quit(); // 退出应用
- }
- });
- app.on('activate', () => {
- if (BrowserWindow.getAllWindows().length === 0) {
- createMainWindow(); // 如果没有窗口打开,则重新创建一个窗口
- }
- });
复制代码
### 2. 创建 `notification.html` 文件
接下来,创建一个名为 `notification.html` 的文件,用于在子窗口中显示内容。
**notification.html**
- html
- <!DOCTYPE html>
- <html lang="zh">
- <head>
- <meta charset="UTF-8">
- <title>通知窗口</title>
- <style>
- body {
- display: flex;
- justify-content: center;
- align-items: center;
- height: 100vh;
- background-color: #f0f0f0;
- font-family: Arial, sans-serif;
- }
- </style>
- </head>
- <body>
- <h1>这是一个通知窗口</h1>
- <p>窗口将在3秒后自动关闭。</p>
- </body>
- </html>
复制代码
### 3. 创建 `index.html` 文件
你还需要一个主窗口的 HTML 文件,例如 `index.html` :
**index.html**
- html
- <!DOCTYPE html>
- <html lang="zh">
- <head>
- <meta charset="UTF-8">
- <title>主窗口</title>
- </head>
- <body>
- <h1>这是主窗口</h1>
- <p>子窗口将在右下角弹出。</p>
- </body>
- </html>
复制代码
### 4. 启动应用
确保你的项目结构正确,然后运行 Electron 应用。你应该能看到主窗口弹出,并且在 3 秒后子窗口会自动关闭。
### 总结
- 使用 `BrowserWindow` 创建主窗口和子窗口。
- 设置子窗口的位置,使其显示在右下角。
- 使用 `setTimeout` 来设置延迟,自动关闭子窗口。
- 这种方法可以在 Electron 应用中实现简单的通知窗口功能。
|
|