Build cross-platform desktop apps with JavaScript, HTML, and CSS
npx @tessl/cli install tessl/npm-electron@37.4.0Electron is a comprehensive framework that enables developers to build cross-platform desktop applications using web technologies including JavaScript, HTML, and CSS. Built on Node.js and Chromium, it provides a runtime environment that combines the power of web technologies with native desktop capabilities, allowing developers to create full-featured desktop applications with familiar web development skills.
npm install electron// Main process (Node.js environment)
const { app, BrowserWindow, Menu, dialog } = require('electron');
// Renderer process (Chromium environment) - requires nodeIntegration: true
const { ipcRenderer, remote } = require('electron');
// Preload script (secure bridge)
const { contextBridge, ipcRenderer } = require('electron');ES6 Modules (when using type: "module"):
import { app, BrowserWindow, Menu, dialog } from 'electron';const { app, BrowserWindow } = require('electron');
const path = require('path');
// Create the main application window
function createWindow() {
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false
}
});
mainWindow.loadFile('index.html');
}
// Application lifecycle
app.whenReady().then(createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});Electron is built around several key components:
Core application management including lifecycle events, process control, and basic app configuration. Essential for all Electron applications.
interface App extends EventEmitter {
whenReady(): Promise<void>;
quit(): void;
exit(exitCode?: number): void;
getPath(name: string): string;
setPath(name: string, path: string): void;
}
declare const app: App;Window creation, management, and view system for building application interfaces. Includes BrowserWindow, webContents, and the new View system.
class BrowserWindow extends EventEmitter {
constructor(options?: BrowserWindowConstructorOptions);
loadURL(url: string, options?: LoadURLOptions): Promise<void>;
loadFile(filePath: string, options?: LoadFileOptions): Promise<void>;
show(): void;
hide(): void;
close(): void;
static getAllWindows(): BrowserWindow[];
static getFocusedWindow(): BrowserWindow | null;
static fromId(id: number): BrowserWindow | null;
}
interface WebContents extends EventEmitter {
loadURL(url: string, options?: LoadURLOptions): Promise<void>;
send(channel: string, ...args: any[]): void;
executeJavaScript(code: string, userGesture?: boolean): Promise<any>;
openDevTools(options?: OpenDevToolsOptions): void;
}Secure communication system between main and renderer processes, including contextBridge for secure API exposure.
interface IpcMain extends EventEmitter {
on(channel: string, listener: (event: IpcMainEvent, ...args: any[]) => void): this;
handle(channel: string, listener: (event: IpcMainInvokeEvent, ...args: any[]) => Promise<any> | any): void;
removeHandler(channel: string): void;
}
interface IpcRenderer extends EventEmitter {
send(channel: string, ...args: any[]): void;
invoke(channel: string, ...args: any[]): Promise<any>;
on(channel: string, listener: (event: IpcRendererEvent, ...args: any[]) => void): this;
}
interface ContextBridge {
exposeInMainWorld(apiKey: string, api: any): void;
exposeInIsolatedWorld(worldId: number, apiKey: string, api: any): void;
}Native system integration including dialogs, notifications, system tray, clipboard, and platform-specific features.
interface Dialog {
showOpenDialog(browserWindow: BrowserWindow | undefined, options: OpenDialogOptions): Promise<OpenDialogReturnValue>;
showSaveDialog(browserWindow: BrowserWindow | undefined, options: SaveDialogOptions): Promise<SaveDialogReturnValue>;
showMessageBox(browserWindow: BrowserWindow | undefined, options: MessageBoxOptions): Promise<MessageBoxReturnValue>;
showErrorBox(title: string, content: string): void;
}
interface Screen extends EventEmitter {
getPrimaryDisplay(): Display;
getAllDisplays(): Display[];
getCursorScreenPoint(): Point;
}
interface Shell {
openExternal(url: string, options?: OpenExternalOptions): Promise<void>;
openPath(path: string): Promise<string>;
showItemInFolder(fullPath: string): void;
trashItem(path: string): Promise<void>;
}Native menu system, including application menus, context menus, and platform-specific UI components like Touch Bar.
class Menu {
static setApplicationMenu(menu: Menu | null): void;
static buildFromTemplate(template: MenuItemConstructorOptions[]): Menu;
static getApplicationMenu(): Menu | null;
popup(options?: PopupOptions): void;
append(menuItem: MenuItem): void;
insert(pos: number, menuItem: MenuItem): void;
}
class MenuItem {
constructor(options: MenuItemConstructorOptions);
}Network requests, custom protocol registration, and session management for handling web resources and custom schemes.
interface Net {
request(options: ClientRequestConstructorOptions | string): ClientRequest;
fetch(input: RequestInfo, init?: RequestInit): Promise<Response>;
}
interface Protocol {
registerSchemesAsPrivileged(customSchemes: CustomScheme[]): void;
handle(scheme: string, handler: ProtocolHandler): void;
unhandle(scheme: string): void;
isProtocolHandled(scheme: string): boolean;
}
interface Session extends EventEmitter {
static fromPartition(partition: string, options?: FromPartitionOptions): Session;
static readonly defaultSession: Session;
fetch(input: RequestInfo, init?: RequestInit): Promise<Response>;
setDisplayMediaRequestHandler(handler: DisplayMediaRequestHandler): void;
}Security features including safe storage, context isolation, sandboxing, and secure communication patterns.
interface SafeStorage {
isEncryptionAvailable(): boolean;
encryptString(plainText: string): Buffer;
decryptString(encrypted: Buffer): string;
}
interface WebFrame extends EventEmitter {
setZoomFactor(factor: number): void;
insertCSS(css: string, options?: InsertCSSOptions): Promise<string>;
executeJavaScript(code: string, userGesture?: boolean): Promise<any>;
}Platform-specific APIs for macOS, Windows, and Linux, including auto-updater, system preferences, and native integrations.
interface SystemPreferences extends EventEmitter {
isDarkMode(): boolean; // macOS
getAccentColor(): string; // Windows
getSystemColor(color: SystemColor): string;
}
interface AutoUpdater extends EventEmitter {
setFeedURL(options: FeedURLOptions): void;
checkForUpdates(): void;
quitAndInstall(): void;
}
interface PowerMonitor extends EventEmitter {
getSystemIdleState(idleThreshold: number): 'active' | 'idle' | 'locked' | 'unknown';
getSystemIdleTime(): number;
}Development tools, debugging utilities, crash reporting, and performance monitoring for building and maintaining Electron applications.
interface CrashReporter {
start(options: CrashReporterStartOptions): void;
getLastCrashReport(): CrashReport | null;
getUploadedReports(): CrashReport[];
}
interface ContentTracing {
getCategories(): Promise<string[]>;
startRecording(options: TraceCategoriesAndOptions | TraceConfig): Promise<void>;
stopRecording(resultFilePath?: string): Promise<string>;
}interface BrowserWindowConstructorOptions {
width?: number;
height?: number;
x?: number;
y?: number;
useContentSize?: boolean;
center?: boolean;
minWidth?: number;
minHeight?: number;
maxWidth?: number;
maxHeight?: number;
resizable?: boolean;
movable?: boolean;
minimizable?: boolean;
maximizable?: boolean;
closable?: boolean;
focusable?: boolean;
alwaysOnTop?: boolean;
fullscreen?: boolean;
fullscreenable?: boolean;
simpleFullscreen?: boolean;
skipTaskbar?: boolean;
kiosk?: boolean;
title?: string;
icon?: NativeImage | string;
show?: boolean;
frame?: boolean;
parent?: BrowserWindow;
modal?: boolean;
acceptFirstMouse?: boolean;
disableAutoHideCursor?: boolean;
autoHideMenuBar?: boolean;
enableLargerThanScreen?: boolean;
backgroundColor?: string;
hasShadow?: boolean;
opacity?: number;
darkTheme?: boolean;
transparent?: boolean;
type?: string;
visualEffectState?: 'followWindow' | 'active' | 'inactive';
titleBarStyle?: 'default' | 'hidden' | 'hiddenInset' | 'customButtonsOnHover';
titleBarOverlay?: TitleBarOverlay | boolean;
trafficLightPosition?: Point;
roundedCorners?: boolean;
fullscreenWindowTitle?: boolean;
thickFrame?: boolean;
vibrancy?: 'appearance-based' | 'light' | 'dark' | 'titlebar' | 'selection' | 'menu' | 'popover' | 'sidebar' | 'medium-light' | 'ultra-dark' | 'header' | 'sheet' | 'window' | 'hud' | 'fullscreen-ui' | 'tooltip' | 'content' | 'under-window' | 'under-page';
zoomToPageWidth?: boolean;
tabbingIdentifier?: string;
webPreferences?: WebPreferences;
}
interface WebPreferences {
devTools?: boolean;
nodeIntegration?: boolean;
nodeIntegrationInWorker?: boolean;
nodeIntegrationInSubFrames?: boolean;
preload?: string;
sandbox?: boolean;
enableRemoteModule?: boolean;
contextIsolation?: boolean;
worldSafeExecuteJavaScript?: boolean;
enableWebSecurity?: boolean;
allowRunningInsecureContent?: boolean;
experimentalFeatures?: boolean;
enableBlinkFeatures?: string;
disableBlinkFeatures?: string;
defaultFontFamily?: DefaultFontFamily;
defaultFontSize?: number;
defaultMonospaceFontSize?: number;
minimumFontSize?: number;
defaultEncoding?: string;
backgroundThrottling?: boolean;
offscreen?: boolean;
webgl?: boolean;
plugins?: boolean;
webSecurity?: boolean;
allowDisplayingInsecureContent?: boolean;
images?: boolean;
textAreasAreResizable?: boolean;
webAudio?: boolean;
navigateOnDragDrop?: boolean;
autoplayPolicy?: 'no-user-gesture-required' | 'user-gesture-required' | 'document-user-activation-required';
disableHtmlFullscreenWindowResize?: boolean;
accessibleTitle?: string;
spellcheck?: boolean;
enableWebSQL?: boolean;
v8CacheOptions?: 'none' | 'code' | 'bypassHeatCheck' | 'bypassHeatCheckAndEagerCompile';
enablePreferredSizeMode?: boolean;
}
interface LoadURLOptions {
httpReferrer?: string | Referrer;
userAgent?: string;
extraHeaders?: string;
postData?: PostData[];
baseURLForDataURL?: string;
}
interface Point {
x: number;
y: number;
}
interface Size {
width: number;
height: number;
}
interface Rectangle {
x: number;
y: number;
width: number;
height: number;
}
interface Display {
id: number;
label: string;
bounds: Rectangle;
workArea: Rectangle;
accelerometerSupport: 'available' | 'unavailable' | 'unknown';
colorSpace: string;
colorDepth: number;
depthPerComponent: number;
displayFrequency: number;
internal: boolean;
monochrome: boolean;
rotation: number;
scaleFactor: number;
size: Size;
touchSupport: 'available' | 'unavailable' | 'unknown';
workAreaSize: Size;
}