تطبيقات شريط النظام والشارات
أنشئ تطبيقات تعمل في شريط النظام أو منطقة الإرساء، وتوفّر وصولًا سريعًا وتعرض شارات للإشعارات غير المقروءة
تطبيقات شريط النظام والشارات درس مجاني في Electron Desktop App Development على CoddyKit. هذا هو الدرس 2 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Electron Desktop App Development، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Electron Desktop App Development 4 دروس في المجموع.
بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.
Intro to Tray & Dock Apps
Welcome! In this lesson, you'll learn how to make your Electron apps live in the system tray or macOS dock. These are great spots for apps that run in the background or need quick access.
The system tray (also known as the notification area) is usually found near the clock on Windows and Linux. On macOS, apps often have icons in the dock or the menu bar at the top.
Why Use Tray/Dock Features?
Integrating with the system tray or dock offers several benefits for your Electron application:
- Quick Access: Users can interact with your app without opening its main window.
- Background Tasks: Ideal for apps that run continuously, like chat clients or utility tools.
- Status Updates: Display simple status indicators or unread notification counts.
- Resource Efficiency: Allows the main window to be hidden, reducing screen clutter.
Creating a Basic Tray Icon
Electron's Tray module allows you to add icons to the system's notification area. You'll need an image file for your icon.
Here's how you initialize a basic tray icon:
const { app, Tray } = require('electron');
const path = require('path');
let tray = null;
app.whenReady().then(() => {
const iconPath = path.join(__dirname, 'icon.png');
tray = new Tray(iconPath);
tray.setToolTip('My First Electron Tray App');
});Tray Icon in Action
Try running this example. Remember to place an icon.png file in the same directory as your main.js. After launching, look for your app's icon in the system tray (Windows/Linux) or menu bar (macOS).
const { app, Tray } = require('electron');
const path = require('path');
let tray = null;
app.whenReady().then(() => {
// IMPORTANT: For this code to run, place an 'icon.png' file
// in the same directory as your main.js file.
const iconPath = path.join(__dirname, 'icon.png');
tray = new Tray(iconPath);
tray.setToolTip('My Simple Tray App');
console.log('Tray icon created. Check your system tray/dock!');
});
app.on('window-all-closed', () => {
// For a tray app, you might want it to stay running even if windows close.
// This example quits if no windows are open and not on macOS.
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('before-quit', () => {
if (tray) tray.destroy(); // Clean up tray icon before quitting
});Interacting with the Tray Icon
A static tray icon isn't very useful! You can make it interactive by listening for events like clicks.
Common actions include showing/hiding the main window or opening a context menu.
You can use tray.on('click', () => { /* action */ }); to handle left-clicks.
Adding a Context Menu
Often, users expect a right-click on a tray icon to open a menu with options. Electron's Menu module is perfect for this.
You define a menu template and then attach it to the tray icon using tray.setContextMenu().
const { Menu } = require('electron');
const contextMenu = Menu.buildFromTemplate([
{ label: 'Option One', type: 'normal', click: () => console.log('Option One clicked!') },
{ label: 'Option Two', type: 'normal', click: () => console.log('Option Two clicked!') },
{ type: 'separator' }, // A visual separator
{ label: 'Quit', role: 'quit' } // Standard quit option
]);
tray.setContextMenu(contextMenu);Tray Menu in Action
This example combines a tray icon with a context menu. Right-click the tray icon to see options to show, hide, or quit the app. Left-click will toggle the window visibility.
Remember to place an icon.png file in the same directory.
const { app, BrowserWindow, Tray, Menu } = require('electron');
const path = require('path');
let mainWindow;
let tray;
function createWindow () {
mainWindow = new BrowserWindow({
width: 400,
height: 300,
show: false, // Start hidden
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
// A very simple HTML content for the window
mainWindow.loadURL(`data:text/html;charset=utf-8,
<h1>Hello from Electron!</h1>
<p>This is a hidden window. Click the tray icon or use its menu.</p>
<button onclick="window.close()">Close Window</button>
`);
}
app.whenReady().then(() => {
createWindow();
const iconPath = path.join(__dirname, 'icon.png'); // Place 'icon.png' here
tray = new Tray(iconPath);
tray.setToolTip('Electron Tray App with Menu');
const contextMenu = Menu.buildFromTemplate([
{ label: 'Show Window', click: () => mainWindow.show() },
{ label: 'Hide Window', click: () => mainWindow.hide() },
{ type: 'separator' },
{ label: 'Quit', click: () => app.quit() }
]);
tray.setContextMenu(contextMenu);
tray.on('click', () => {
mainWindow.isVisible() ? mainWindow.hide() : mainWindow.show();
});
// Ensure app doesn't quit when window is closed
mainWindow.on('close', (event) => {
if (!app.isQuitting) { // Only hide if not explicitly quitting
event.preventDefault();
mainWindow.hide();
}
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
});
app.on('window-all-closed', () => {
// If not macOS, and no tray icon, then quit
if (process.platform !== 'darwin' && !tray) {
app.quit();
}
});
app.on('before-quit', () => {
app.isQuitting = true; // Set a flag
if (tray) tray.destroy();
});Dock Badges (macOS Only)
On macOS, applications can display a 'badge' on their dock icon. This is typically used to show a count of unread items or notifications.
Electron provides the app.setBadgeCount(count) method for this. Set count to 0 to clear the badge. This feature is specific to macOS.
const { app } = require('electron');
// To set a badge:
if (process.platform === 'darwin') {
app.setBadgeCount(5);
}
// To clear a badge:
if (process.platform === 'darwin') {
app.setBadgeCount(0);
}Dock Badge in Action
This example demonstrates setting and clearing a dock badge. Run this application on macOS and observe its dock icon. It will set a badge after 3 seconds, then clear it after 8 seconds.
This feature will not work on Windows or Linux.
const { app, BrowserWindow } = require('electron');
const path = require('path');
let mainWindow;
function createWindow () {
mainWindow = new BrowserWindow({
width: 400,
height: 300,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
mainWindow.loadURL(`data:text/html;charset=utf-8,
<h1>Electron Dock Badge Demo</h1>
<p>Check your macOS dock icon for a badge!</p>
<p>The badge will appear shortly after launch.</p>
`);
}
app.whenReady().then(() => {
createWindow();
if (process.platform === 'darwin') {
// Set a badge count after a short delay
setTimeout(() => {
app.setBadgeCount(5);
console.log('Dock badge set to 5. Look at your macOS dock icon!');
}, 3000); // 3 seconds delay
// Clear the badge after another delay
setTimeout(() => {
app.setBadgeCount(0);
console.log('Dock badge cleared. Icon should be normal.');
}, 8000); // 8 seconds total delay
} else {
console.log('Dock badges are a macOS-specific feature and will not appear on this OS.');
}
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});Quick Check: Tray Icons
You've learned about creating tray icons and setting dock badges. Let's quickly review!
Recap: Tray & Badges
Great job! You've learned how to integrate your Electron app more deeply with the native OS:
- The
Traymodule lets you add an icon to the system tray or macOS menu bar. - You can attach a
Menuto your tray icon for right-click options. - On macOS,
app.setBadgeCount()allows you to display notification badges on the dock icon.
These features enhance the user experience by providing quick access and status updates.
الأسئلة الشائعة
هل درس «تطبيقات شريط النظام والشارات» مجاني؟
نعم — نص درس «تطبيقات شريط النظام والشارات» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 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 يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.
جميع الدروس في هذه الدورة
- العمل مع الوحدات الأصلية
- تطبيقات شريط النظام والشارات
- التقاط الشاشة والوسائط
- مراقبة الطاقة والعتاد