Native system integration including dialogs, notifications, system tray, clipboard, and platform-specific features.
Native system dialogs for file operations and user notifications.
/**
* Display native system dialogs for opening and saving files, alerting, etc.
*/
interface Dialog {
/** Shows a message box and returns a promise that resolves when the message box is closed */
showMessageBox(browserWindow: BrowserWindow | undefined, options: MessageBoxOptions): Promise<MessageBoxReturnValue>;
/** Shows a message box synchronously */
showMessageBoxSync(browserWindow: BrowserWindow | undefined, options: MessageBoxOptions): number;
/** Shows an error box with the given title and message */
showErrorBox(title: string, content: string): void;
/** Shows a dialog for opening files or directories */
showOpenDialog(browserWindow: BrowserWindow | undefined, options: OpenDialogOptions): Promise<OpenDialogReturnValue>;
/** Shows a dialog for opening files or directories synchronously */
showOpenDialogSync(browserWindow: BrowserWindow | undefined, options: OpenDialogOptions): string[] | undefined;
/** Shows a dialog for saving files */
showSaveDialog(browserWindow: BrowserWindow | undefined, options: SaveDialogOptions): Promise<SaveDialogReturnValue>;
/** Shows a dialog for saving files synchronously */
showSaveDialogSync(browserWindow: BrowserWindow | undefined, options: SaveDialogOptions): string | undefined;
/** Shows the certificate trust dialog in macOS */
showCertificateTrustDialog(browserWindow: BrowserWindow | undefined, options: CertificateTrustDialogOptions): Promise<void>;
/** Shows the certificate trust dialog in macOS synchronously */
showCertificateTrustDialogSync(browserWindow: BrowserWindow | undefined, options: CertificateTrustDialogOptions): void;
}
declare const dialog: Dialog;Usage Examples:
const { dialog, BrowserWindow } = require('electron');
// Show message box
async function showInfo() {
const result = await dialog.showMessageBox(null, {
type: 'info',
title: 'Information',
message: 'This is an information message',
detail: 'Additional details here',
buttons: ['OK', 'Cancel'],
defaultId: 0,
cancelId: 1
});
console.log('User clicked:', result.response === 0 ? 'OK' : 'Cancel');
}
// File picker
async function selectFile() {
const result = await dialog.showOpenDialog(mainWindow, {
title: 'Select a file',
defaultPath: os.homedir(),
filters: [
{ name: 'Text Files', extensions: ['txt', 'md'] },
{ name: 'Images', extensions: ['png', 'jpg', 'gif'] },
{ name: 'All Files', extensions: ['*'] }
],
properties: ['openFile', 'multiSelections']
});
if (!result.canceled) {
console.log('Selected files:', result.filePaths);
return result.filePaths;
}
}
// Save dialog
async function saveFile(content) {
const result = await dialog.showSaveDialog(mainWindow, {
title: 'Save file',
defaultPath: path.join(os.homedir(), 'document.txt'),
filters: [
{ name: 'Text Files', extensions: ['txt'] },
{ name: 'All Files', extensions: ['*'] }
]
});
if (!result.canceled && result.filePath) {
await fs.writeFile(result.filePath, content);
console.log('File saved to:', result.filePath);
}
}
// Error dialog
function showError(error) {
dialog.showErrorBox('Application Error', error.message);
}Display information and management for multi-monitor setups.
/**
* Retrieve information about screen size, displays, cursor position, etc.
*/
interface Screen extends EventEmitter {
/** Returns the current absolute position of the mouse pointer */
getCursorScreenPoint(): Point;
/** Returns the primary display */
getPrimaryDisplay(): Display;
/** Returns an array of displays that are currently available */
getAllDisplays(): Display[];
/** Returns the display nearest the specified point */
getDisplayNearestPoint(point: Point): Display;
/** Returns the display that most closely intersects the provided bounds */
getDisplayMatching(rect: Rectangle): Display;
/** Converts a screen physical point to a screen DIP point */
screenToDipPoint(point: Point): Point;
/** Converts a screen DIP point to a screen physical point */
dipToScreenPoint(point: Point): Point;
/** Converts a screen physical rect to a screen DIP rect */
screenToDipRect(window: BrowserWindow | null, rect: Rectangle): Rectangle;
/** Converts a screen DIP rect to a screen physical rect */
dipToScreenRect(window: BrowserWindow | null, rect: Rectangle): Rectangle;
}
declare const screen: Screen;Usage Examples:
const { screen, BrowserWindow } = require('electron');
// Get display information
function getDisplayInfo() {
const displays = screen.getAllDisplays();
const primaryDisplay = screen.getPrimaryDisplay();
console.log('Primary display:', primaryDisplay);
console.log('All displays:', displays);
return {
primary: primaryDisplay,
all: displays,
count: displays.length
};
}
// Position window on specific display
function createWindowOnDisplay(displayIndex = 0) {
const displays = screen.getAllDisplays();
const targetDisplay = displays[displayIndex] || displays[0];
const window = new BrowserWindow({
x: targetDisplay.bounds.x + 50,
y: targetDisplay.bounds.y + 50,
width: 800,
height: 600
});
return window;
}
// Monitor cursor position
function trackCursor() {
const cursorPosition = screen.getCursorScreenPoint();
const display = screen.getDisplayNearestPoint(cursorPosition);
console.log('Cursor at:', cursorPosition);
console.log('On display:', display.label);
}
// Handle display changes
screen.on('display-added', (event, newDisplay) => {
console.log('Display added:', newDisplay);
});
screen.on('display-removed', (event, oldDisplay) => {
console.log('Display removed:', oldDisplay);
});
screen.on('display-metrics-changed', (event, display, changedMetrics) => {
console.log('Display metrics changed:', display, changedMetrics);
});Desktop integration utilities for opening files and URLs.
/**
* Manage files and URLs using their default applications
*/
interface Shell {
/** Show the given file in a file manager */
showItemInFolder(fullPath: string): void;
/** Open the given file in the desktop's default manner */
openPath(path: string): Promise<string>;
/** Open the given external protocol URL in the desktop's default manner */
openExternal(url: string, options?: OpenExternalOptions): Promise<void>;
/** Move the given file to trash */
trashItem(path: string): Promise<void>;
/** Play the beep sound */
beep(): void;
/** Creates or updates a shortcut link at shortcutPath */
writeShortcutLink(shortcutPath: string, operation: 'create' | 'update' | 'replace', options: ShortcutDetails): boolean;
/** Resolves the shortcut link at shortcutPath */
readShortcutLink(shortcutPath: string): ShortcutDetails;
}
declare const shell: Shell;Usage Examples:
const { shell } = require('electron');
// Open URLs in default browser
async function openWebsite(url) {
try {
await shell.openExternal(url);
console.log('Opened URL:', url);
} catch (error) {
console.error('Failed to open URL:', error);
}
}
// Open file with default application
async function openFile(filePath) {
try {
const result = await shell.openPath(filePath);
if (result) {
console.log('Error opening file:', result);
} else {
console.log('File opened successfully');
}
} catch (error) {
console.error('Failed to open file:', error);
}
}
// Show file in folder
function revealFile(filePath) {
shell.showItemInFolder(filePath);
}
// Move to trash
async function deleteFile(filePath) {
try {
await shell.trashItem(filePath);
console.log('File moved to trash:', filePath);
} catch (error) {
console.error('Failed to trash file:', error);
}
}
// System beep
function playBeep() {
shell.beep();
}System clipboard access for text, HTML, and images.
/**
* Perform copy and paste operations on the system clipboard
*/
interface Clipboard {
/** Returns the content in the clipboard as plain text */
readText(type?: 'selection' | 'clipboard'): string;
/** Writes the text into the clipboard as plain text */
writeText(text: string, type?: 'selection' | 'clipboard'): void;
/** Returns the content in the clipboard as markup */
readHTML(type?: 'selection' | 'clipboard'): string;
/** Writes markup to the clipboard */
writeHTML(markup: string, type?: 'selection' | 'clipboard'): void;
/** Returns the content in the clipboard as a NativeImage */
readImage(type?: 'selection' | 'clipboard'): NativeImage;
/** Writes image to the clipboard */
writeImage(image: NativeImage, type?: 'selection' | 'clipboard'): void;
/** Returns the content in the clipboard as RTF */
readRTF(type?: 'selection' | 'clipboard'): string;
/** Writes the text into the clipboard in RTF */
writeRTF(text: string, type?: 'selection' | 'clipboard'): void;
/** Returns an Object containing title and url keys representing the bookmark in the clipboard */
readBookmark(): { title: string; url: string };
/** Writes the title and url into the clipboard as a bookmark */
writeBookmark(title: string, url: string, type?: 'selection' | 'clipboard'): void;
/** Returns the content in the clipboard for the specified format */
readBuffer(format: string): Buffer;
/** Writes the buffer into the clipboard for the specified format */
writeBuffer(format: string, buffer: Buffer, type?: 'selection' | 'clipboard'): void;
/** Returns an array of supported formats for the clipboard type */
availableFormats(type?: 'selection' | 'clipboard'): string[];
/** Returns whether the clipboard supports the specified format */
has(format: string, type?: 'selection' | 'clipboard'): boolean;
/** Reads findText from the clipboard on macOS */
readFindText(): string;
/** Writes the findText into the clipboard on macOS */
writeFindText(text: string): void;
/** Clears the clipboard content */
clear(type?: 'selection' | 'clipboard'): void;
/** Writes data to the clipboard */
write(data: Data, type?: 'selection' | 'clipboard'): void;
}
declare const clipboard: Clipboard;Usage Examples:
const { clipboard, nativeImage } = require('electron');
// Text operations
function copyText(text) {
clipboard.writeText(text);
console.log('Copied to clipboard:', text);
}
function pasteText() {
const text = clipboard.readText();
console.log('Pasted from clipboard:', text);
return text;
}
// HTML operations
function copyHTML(html) {
clipboard.writeHTML(html);
}
function pasteHTML() {
return clipboard.readHTML();
}
// Image operations
function copyImage(imagePath) {
const image = nativeImage.createFromPath(imagePath);
clipboard.writeImage(image);
}
function pasteImage() {
const image = clipboard.readImage();
if (!image.isEmpty()) {
return image;
}
return null;
}
// Multiple data types
function copyRichContent(text, html, imagePath) {
const image = imagePath ? nativeImage.createFromPath(imagePath) : null;
clipboard.write({
text: text,
html: html,
image: image
});
}
// Check available formats
function getClipboardInfo() {
const formats = clipboard.availableFormats();
console.log('Available formats:', formats);
return {
hasText: clipboard.has('text/plain'),
hasHTML: clipboard.has('text/html'),
hasImage: clipboard.has('image/png'),
formats: formats
};
}System tray/notification area icons and menus.
/**
* Add icons and context menus to the system's notification area
*/
class Tray extends EventEmitter {
/** Creates a new tray icon associated with the image */
constructor(image: NativeImage | string, guid?: string);
/** Destroys the tray icon immediately */
destroy(): void;
/** Sets the image associated with this tray icon */
setImage(image: NativeImage | string): void;
/** Sets the image associated with this tray icon when pressed on macOS */
setPressedImage(image: NativeImage | string): void;
/** Sets the hover text for this tray icon */
setToolTip(toolTip: string): void;
/** Sets the title displayed next to the tray icon in the status bar (macOS only) */
setTitle(title: string, options?: TitleOptions): void;
/** Returns the title displayed next to the tray icon in the status bar */
getTitle(): string;
/** Sets when the tray's icon background becomes highlighted (macOS only) */
setIgnoreDoubleClickEvents(ignore: boolean): void;
/** Returns whether double click events will be ignored */
getIgnoreDoubleClickEvents(): boolean;
/** Displays a tray balloon */
displayBalloon(options: DisplayBalloonOptions): void;
/** Removes a tray balloon */
removeBalloon(): void;
/** Returns focus to the taskbar notification area */
focus(): void;
/** Pops up the context menu of the tray icon */
popUpContextMenu(menu?: Menu, position?: Point): void;
/** Closes an open context menu */
closeContextMenu(): void;
/** Sets the context menu for this icon */
setContextMenu(menu: Menu | null): void;
/** Returns the bounds of this tray icon */
getBounds(): Rectangle;
/** Returns whether the tray icon is destroyed */
isDestroyed(): boolean;
}Usage Examples:
const { Tray, Menu, nativeImage, BrowserWindow } = require('electron');
let tray = null;
function createTray() {
// Create tray icon
const icon = nativeImage.createFromPath('/path/to/icon.png');
tray = new Tray(icon);
// Set tooltip
tray.setToolTip('My Electron App');
// Create context menu
const contextMenu = Menu.buildFromTemplate([
{
label: 'Show App',
click: () => {
const window = BrowserWindow.getFocusedWindow() || BrowserWindow.getAllWindows()[0];
if (window) {
window.show();
window.focus();
}
}
},
{
label: 'Settings',
click: openSettings
},
{ type: 'separator' },
{
label: 'Quit',
click: () => {
app.quit();
}
}
]);
// Set context menu
tray.setContextMenu(contextMenu);
// Handle click events
tray.on('click', () => {
const window = BrowserWindow.getFocusedWindow() || BrowserWindow.getAllWindows()[0];
if (window) {
if (window.isVisible()) {
window.hide();
} else {
window.show();
window.focus();
}
}
});
tray.on('double-click', () => {
const window = BrowserWindow.getFocusedWindow() || BrowserWindow.getAllWindows()[0];
if (window) {
window.show();
window.focus();
}
});
return tray;
}
// Update tray based on app state
function updateTray(status) {
if (!tray) return;
const iconName = status === 'busy' ? 'icon-busy.png' : 'icon-idle.png';
const icon = nativeImage.createFromPath(`/path/to/${iconName}`);
tray.setImage(icon);
tray.setToolTip(`My App - ${status}`);
}
// Show balloon notification (Windows)
function showBalloon(title, message) {
if (tray && process.platform === 'win32') {
tray.displayBalloon({
icon: nativeImage.createFromPath('/path/to/icon.png'),
title: title,
content: message
});
}
}Cross-platform system notifications.
/**
* Create OS desktop notifications
*/
class Notification extends EventEmitter {
/** Create a new notification */
constructor(options?: NotificationConstructorOptions);
/** Immediately shows the notification to the user */
show(): void;
/** Dismisses the notification */
close(): void;
/** A string property representing the title of the notification */
title: string;
/** A string property representing the subtitle of the notification */
subtitle: string;
/** A string property representing the body text of the notification */
body: string;
/** A string property representing the reply placeholder of the notification */
replyPlaceholder: string;
/** A string property representing the sound file to play when the notification is shown */
sound: string;
/** A NotificationAction[] property representing the actions of the notification */
actions: NotificationAction[];
/** A boolean property indicating whether the notification is silent */
silent: boolean;
/** A boolean property indicating whether the notification has a reply action */
hasReply: boolean;
/** A string property representing the urgency level of the notification */
urgency: 'normal' | 'critical' | 'low';
/** A string property representing the close button text of the notification */
closeButtonText: string;
/** Returns whether or not desktop notifications are supported on the current system */
static isSupported(): boolean;
}Usage Examples:
const { Notification } = require('electron');
// Check if notifications are supported
if (Notification.isSupported()) {
console.log('Notifications are supported');
} else {
console.log('Notifications are not supported');
}
// Simple notification
function showSimpleNotification() {
const notification = new Notification({
title: 'Basic Notification',
body: 'This is a basic notification message'
});
notification.show();
}
// Rich notification with actions
function showRichNotification() {
const notification = new Notification({
title: 'New Message',
subtitle: 'From John Doe',
body: 'Hey there! How are you doing?',
icon: '/path/to/avatar.png',
sound: 'default',
hasReply: true,
replyPlaceholder: 'Type your reply...',
actions: [
{
type: 'button',
text: 'Mark as Read'
},
{
type: 'button',
text: 'Archive'
}
]
});
// Handle events
notification.on('show', () => {
console.log('Notification shown');
});
notification.on('click', () => {
console.log('Notification clicked');
// Bring app to foreground
const window = BrowserWindow.getFocusedWindow() || BrowserWindow.getAllWindows()[0];
if (window) {
window.show();
window.focus();
}
});
notification.on('reply', (event, reply) => {
console.log('User replied:', reply);
// Handle reply
});
notification.on('action', (event, index) => {
console.log('Action clicked:', index);
if (index === 0) {
// Mark as read
} else if (index === 1) {
// Archive
}
});
notification.show();
}
// Notification with urgency
function showUrgentNotification() {
const notification = new Notification({
title: 'System Alert',
body: 'This requires immediate attention!',
urgency: 'critical',
sound: 'default'
});
notification.show();
}interface MessageBoxOptions {
type?: 'none' | 'info' | 'error' | 'question' | 'warning';
buttons?: string[];
defaultId?: number;
title?: string;
message: string;
detail?: string;
checkboxLabel?: string;
checkboxChecked?: boolean;
icon?: NativeImage;
textWidth?: number;
cancelId?: number;
noLink?: boolean;
normalizeAccessKeys?: boolean;
}
interface MessageBoxReturnValue {
response: number;
checkboxChecked: boolean;
}
interface OpenDialogOptions {
title?: string;
defaultPath?: string;
buttonLabel?: string;
filters?: FileFilter[];
properties?: Array<'openFile' | 'openDirectory' | 'multiSelections' | 'showHiddenFiles' | 'createDirectory' | 'promptToCreate' | 'noResolveAliases' | 'treatPackageAsDirectory' | 'dontAddToRecent'>;
message?: string;
securityScopedBookmarks?: boolean;
}
interface OpenDialogReturnValue {
canceled: boolean;
filePaths: string[];
bookmarks?: string[];
}
interface SaveDialogOptions {
title?: string;
defaultPath?: string;
buttonLabel?: string;
filters?: FileFilter[];
message?: string;
nameFieldLabel?: string;
showsTagField?: boolean;
properties?: Array<'showHiddenFiles' | 'createDirectory' | 'showOverwriteConfirmation' | 'dontAddToRecent'>;
securityScopedBookmarks?: boolean;
}
interface SaveDialogReturnValue {
canceled: boolean;
filePath?: string;
bookmark?: string;
}
interface FileFilter {
name: string;
extensions: string[];
}
interface OpenExternalOptions {
activate?: boolean;
workingDirectory?: string;
}
interface ShortcutDetails {
target: string;
cwd?: string;
args?: string;
description?: string;
icon?: string;
iconIndex?: number;
appUserModelId?: string;
toastActivatorClsid?: string;
}
interface Data {
text?: string;
html?: string;
image?: NativeImage;
rtf?: string;
bookmark?: string;
}
interface TitleOptions {
fontType?: 'monospaced' | 'monospacedDigit';
}
interface DisplayBalloonOptions {
icon?: NativeImage | string;
title: string;
content: string;
largeIcon?: boolean;
noSound?: boolean;
respectQuietTime?: boolean;
}
interface NotificationConstructorOptions {
title?: string;
subtitle?: string;
body?: string;
silent?: boolean;
icon?: string | NativeImage;
hasReply?: boolean;
timeoutType?: 'default' | 'never';
replyPlaceholder?: string;
sound?: string;
urgency?: 'normal' | 'critical' | 'low';
actions?: NotificationAction[];
closeButtonText?: string;
toastXml?: string;
}
interface NotificationAction {
type: 'button';
text: string;
}
interface CertificateTrustDialogOptions {
certificate: Certificate;
message: string;
}
interface Certificate {
data: string;
issuer: CertificatePrincipal;
issuerName: string;
issuerCert: Certificate;
subject: CertificatePrincipal;
subjectName: string;
serialNumber: string;
validStart: number;
validExpiry: number;
fingerprint: string;
}
interface CertificatePrincipal {
commonName: string;
organizations: string[];
organizationUnits: string[];
locality: string;
state: string;
country: string;
}