0Pricing
Electron Desktop App Development · Урок

Диалоговые окна и уведомления

Используйте нативные диалоговые окна для выбора файлов, отображения сообщений и системных уведомлений, обеспечивая единообразный и ненавязчивый пользовательский опыт.

«Диалоговые окна и уведомления» — бесплатный урок Electron Desktop App Development на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Electron Desktop App Development, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Electron Desktop App Development содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Bridging Web and Desktop

Welcome to Lesson 2! In this lesson, we'll learn how to make your Electron app feel truly native by interacting with the operating system.

Desktop applications often need to ask users to select files, confirm actions, or provide timely updates. Electron provides dedicated modules for these tasks: Dialogs and Notifications.

Electron's `dialog` Module

The dialog module allows your Electron app to display native system dialogs for opening and saving files, or showing alert messages.

  • Native Feel: These dialogs match the look and feel of the user's operating system (Windows, macOS, Linux).
  • Blocking Interaction: Dialogs typically block the application's UI until the user interacts with them.
  • Main Process Only: For security and consistency, the dialog module can only be used from the main process.

Selecting Files with `showOpenDialog`

The dialog.showOpenDialog() method lets users select files or directories from their system. It returns a Promise that resolves with the selected paths or indicates if the dialog was canceled.

Key options include:

  • properties: An array like ['openFile', 'multiSelections'] to control selection type.
  • filters: An array of objects like { name: 'Images', extensions: ['jpg', 'png'] } to limit file types.

Code Demo: Open File Dialog

Try running this example. It will launch a simple Electron window and immediately display a native 'Open File' dialog. Select a file and check the console output!

const { app, BrowserWindow, dialog } = require('electron');
const path = require('path');

function createWindow() {
  const mainWindow = new BrowserWindow({
    width: 600,
    height: 400,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      contextIsolation: true
    }
  });

  mainWindow.loadURL('about:blank'); // Load a blank page

  mainWindow.webContents.on('did-finish-load', async () => {
    const result = await dialog.showOpenDialog(mainWindow, {
      title: 'Select a File',
      properties: ['openFile'],
      filters: [
        { name: 'Text Files', extensions: ['txt'] },
        { name: 'All Files', extensions: ['*'] }
      ]
    });
    if (!result.canceled) {
      console.log('Selected file:', result.filePaths[0]);
    } else {
      console.log('File selection canceled.');
    }
  });
}

app.whenReady().then(() => {
  createWindow();

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow();
    }
  });
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

Saving User Data with `showSaveDialog`

When your app needs to save user-generated content, dialog.showSaveDialog() is your go-to. It prompts the user for a location and filename to save a file.

Useful options include:

  • defaultPath: A suggested path or filename (e.g., app.getPath('documents') + '/untitled.txt').
  • filters: Similar to showOpenDialog, to suggest file types.

The dialog returns the chosen file path, or undefined if canceled.

const { app, BrowserWindow, dialog } = require('electron');
const path = require('path');

function createWindow() {
  const mainWindow = new BrowserWindow({ width: 600, height: 400 });
  mainWindow.loadURL('about:blank');

  mainWindow.webContents.on('did-finish-load', async () => {
    const result = await dialog.showSaveDialog(mainWindow, {
      title: 'Save Your File',
      defaultPath: app.getPath('documents') + '/my_document.txt',
      filters: [
        { name: 'Text Files', extensions: ['txt'] },
        { name: 'All Files', extensions: ['*'] }
      ]
    });
    if (!result.canceled) {
      console.log('File will be saved to:', result.filePath);
      // In a real app, you'd write content to result.filePath here
    } else {
      console.log('Save operation canceled.');
    }
  });
}

app.whenReady().then(createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});

Alerting Users with `showMessageBox`

For general alerts, confirmations, or error messages, use dialog.showMessageBox(). This displays a native message box with customizable buttons and text.

Key options:

  • type: 'none', 'info', 'warning', 'error', 'question'.
  • buttons: An array of button labels (e.g., ['Save', 'Discard', 'Cancel']).
  • message: The main message text.
  • detail: Additional, more detailed information.

It returns the index of the button clicked by the user.

const { app, BrowserWindow, dialog } = require('electron');
const path = require('path');

function createWindow() {
  const mainWindow = new BrowserWindow({ width: 600, height: 400 });
  mainWindow.loadURL('about:blank');

  mainWindow.webContents.on('did-finish-load', async () => {
    const result = await dialog.showMessageBox(mainWindow, {
      type: 'question',
      title: 'Exit Application',
      message: 'Do you want to save your changes?',
      detail: 'Unsaved changes will be lost if you proceed without saving.',
      buttons: ['Save', 'Discard', 'Cancel'],
      defaultId: 0,
      cancelId: 2
    });

    if (result.response === 0) {
      console.log('User chose to Save.');
    } else if (result.response === 1) {
      console.log('User chose to Discard.');
    } else {
      console.log('User chose to Cancel.');
    }
  });
}

app.whenReady().then(createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});

System Notifications with `Notification`

While dialogs demand immediate attention, the Notification module provides a non-intrusive way to inform users about events. These appear in the operating system's notification center.

  • Non-Blocking: Notifications don't interrupt the user's workflow.
  • Timely Info: Ideal for background task completion, new messages, or status updates.
  • Main or Renderer: Can be used from both processes.

Sending a Simple Notification

Sending a notification is straightforward. You create a new Notification instance and call its show() method.

Common options include:

  • title: The main title of the notification.
  • body: The detailed text content.
  • icon: An optional path to an image icon.

It's good practice to check Notification.isSupported() before attempting to show a notification.

const { app, BrowserWindow, Notification } = require('electron');
const path = require('path');

function createWindow() {
  const mainWindow = new BrowserWindow({ width: 600, height: 400 });
  mainWindow.loadURL('about:blank');

  mainWindow.webContents.on('did-finish-load', () => {
    if (Notification.isSupported()) {
      new Notification({
        title: 'Electron App Update',
        body: 'A new version is available! Click to install.',
        // icon: path.join(__dirname, 'icon.png') // Optional
      }).show();
      console.log('Notification sent!');
    } else {
      console.log('Notifications are not supported on this system.');
    }
  });
}

app.whenReady().then(createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});

Interactive Notifications

Notifications can be more than just static messages. You can add interactivity by listening for events like click or close. This allows users to take action directly from the notification itself.

For example, clicking a 'New Message' notification could bring the app window to the foreground or open a specific chat.

const { app, BrowserWindow, Notification } = require('electron');
const path = require('path');

function createWindow() {
  const mainWindow = new BrowserWindow({ width: 600, height: 400 });
  mainWindow.loadURL('about:blank');

  mainWindow.webContents.on('did-finish-load', () => {
    if (Notification.isSupported()) {
      const myNotification = new Notification({
        title: 'New Message!',
        body: 'You have 3 unread messages.',
        silent: false // Play a sound
      });

      myNotification.on('click', () => {
        console.log('Notification clicked! Opening messages...');
        mainWindow.show(); // Bring the window to front
      });

      myNotification.show();
      console.log('Interactive notification sent.');
    } else {
      console.log('Notifications not supported.');
    }
  });
}

app.whenReady().then(createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});

Dialogs vs. Notifications: When to Use Which?

Choosing between a dialog and a notification depends on the urgency and required user interaction:

  • Dialogs: Use for critical information, user input (file selection, save location), or actions that block the app until resolved. They demand immediate attention.
  • Notifications: Use for non-critical, time-sensitive information that doesn't require immediate action. They inform without interrupting the user's flow.

Always aim for a seamless and intuitive user experience by selecting the appropriate interaction method.

Quick Check: Dialogs or Notifications?

Which of the following scenarios are best suited for using Electron's dialog module? Select all that apply.

Recap & Next Steps

Great job! You've learned how to interact with the native operating system using Electron's dialog and Notification modules.

  • dialog: For critical, blocking interactions like file selection, saving, and message boxes. Only in the main process.
  • Notification: For non-blocking, informative alerts that appear in the system notification center. Can be used in both processes.

Mastering these features helps your Electron app feel truly integrated into the user's desktop environment. Next up, we'll explore how to open external links and files using the shell module!

Часто задаваемые вопросы

Урок «Диалоговые окна и уведомления» бесплатный?

Да — полный текст урока «Диалоговые окна и уведомления» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Electron Desktop App Development, подпишись на CoddyKit PRO. Курс Electron Desktop App Development содержит 4 уроков всего.

Чему я научусь в уроке «Диалоговые окна и уведомления»?

Используйте нативные диалоговые окна для выбора файлов, отображения сообщений и системных уведомлений, обеспечивая единообразный и ненавязчивый пользовательский опыт. Ты практикуешь Electron Desktop App Development с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Electron Desktop App Development?

Предыдущий опыт не требуется. Electron Desktop App Development на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.

Сколько времени занимает урок «Диалоговые окна и уведомления»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Electron Desktop App Development?

Да. Каждый урок Electron Desktop App Development включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Нативные и контекстные меню
  2. Диалоговые окна и уведомления
  3. Интеграция с оболочкой
  4. Глобальные сочетания клавиш и доступ к буферу обмена
← Назад к Electron Desktop App Development