Window creation, management, and view system for building application interfaces. Includes BrowserWindow, webContents, and the new View system.
Primary application window class for creating and managing windows.
/**
* Create and control browser windows
*/
class BrowserWindow extends EventEmitter {
/** Create a new BrowserWindow with native properties set by options */
constructor(options?: BrowserWindowConstructorOptions);
/** Same as webContents.loadURL(url[, options]) */
loadURL(url: string, options?: LoadURLOptions): Promise<void>;
/** Same as webContents.loadFile(filePath[, options]) */
loadFile(filePath: string, options?: LoadFileOptions): Promise<void>;
/** Shows and gives focus to the window */
show(): void;
/** Shows the window but doesn't focus on it */
showInactive(): void;
/** Hides the window */
hide(): void;
/** Try to close the window. Same as user manually clicking close button */
close(): void;
/** Forcefully closes the window */
destroy(): void;
/** Focuses on the window */
focus(): void;
/** Removes focus from the window */
blur(): void;
/** Returns whether the window is focused */
isFocused(): boolean;
/** Returns whether the window is destroyed */
isDestroyed(): boolean;
/** Returns whether the window is visible to the user */
isVisible(): boolean;
/** Returns whether the window is minimized */
isMinimized(): boolean;
/** Returns whether the window is maximized */
isMaximized(): boolean;
/** Returns whether the window is in fullscreen mode */
isFullScreen(): boolean;
/** Maximizes the window */
maximize(): void;
/** Unmaximizes the window */
unmaximize(): void;
/** Minimizes the window */
minimize(): void;
/** Restores the window from minimized state to its previous state */
restore(): void;
/** Enters fullscreen mode */
setFullScreen(flag: boolean): void;
/** Sets whether the window should be in simple fullscreen mode */
setSimpleFullScreen(flag: boolean): void;
/** Returns whether the window is in simple fullscreen mode */
isSimpleFullScreen(): boolean;
/** Returns whether the window is in normal state (not maximized, not minimized, not in fullscreen mode) */
isNormal(): boolean;
/** This will make a window maintain an aspect ratio */
setAspectRatio(aspectRatio: number, extraSize?: Size): void;
/** Uses Quick Look to preview a file at a given path (macOS) */
previewFile(path: string, displayName?: string): void;
/** Closes the currently open Quick Look panel (macOS) */
closeFilePreview(): void;
/** Resizes and moves the window to the supplied bounds */
setBounds(bounds: Partial<Rectangle>, animate?: boolean): void;
/** Returns an object that contains the window's width, height, x and y values */
getBounds(): Rectangle;
/** Returns the background color of the window */
getBackgroundColor(): string;
/** Sets the background color of the window */
setBackgroundColor(backgroundColor: string): void;
/** Returns whether the window has a shadow */
hasShadow(): boolean;
/** Sets whether the window should have a shadow */
setHasShadow(hasShadow: boolean): void;
/** Returns the opacity of the window */
getOpacity(): number;
/** Sets the opacity of the window */
setOpacity(opacity: number): void;
/** Sets a 16 x 16 pixel overlay onto the current taskbar icon */
setOverlayIcon(overlay: NativeImage | null, description: string): void;
/** Sets the pathname of the file the window represents */
setRepresentedFilename(filename: string): void;
/** Returns the pathname of the file the window represents */
getRepresentedFilename(): string;
/** Specifies whether the window's document has been edited */
setDocumentEdited(edited: boolean): void;
/** Whether the window's document has been edited */
isDocumentEdited(): boolean;
/** Opens the developer tools */
openDevTools(options?: OpenDevToolsOptions): void;
/** Closes the developer tools */
closeDevTools(): void;
/** Returns whether the developer tools are opened */
isDevToolsOpened(): boolean;
/** Returns whether the developer tools view is focused */
isDevToolsFocused(): boolean;
/** Toggles the developer tools */
toggleDevTools(): void;
/** Inspects the element at position (x, y) */
inspectElement(x: number, y: number): void;
/** Opens the developer tools for the service worker context */
inspectServiceWorker(): void;
/** Opens the developer tools for the shared worker context */
inspectSharedWorker(): void;
/** Get all BrowserWindow instances */
static getAllWindows(): BrowserWindow[];
/** Get the window that is focused in this application */
static getFocusedWindow(): BrowserWindow | null;
/** Find a window according to the webContents it owns */
static fromWebContents(webContents: WebContents): BrowserWindow | null;
/** Find a window according to its ID */
static fromId(id: number): BrowserWindow | null;
/** A WebContents object this window owns */
readonly webContents: WebContents;
/** A integer representing the unique ID of the window */
readonly id: number;
/** A WebContents object for the devtools window of this window */
readonly devToolsWebContents: WebContents | null;
}Usage Examples:
const { BrowserWindow } = require('electron');
// Create a basic window
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: path.join(__dirname, 'preload.js')
}
});
// Load content
mainWindow.loadFile('index.html');
// Handle window events
mainWindow.on('closed', () => {
mainWindow = null;
});
mainWindow.on('ready-to-show', () => {
mainWindow.show();
});
// Window management
mainWindow.maximize();
mainWindow.setFullScreen(true);
mainWindow.center();
// Developer tools
mainWindow.webContents.openDevTools();
// Get all windows
const allWindows = BrowserWindow.getAllWindows();
console.log(`Total windows: ${allWindows.length}`);Controls and communicates with a renderer process.
/**
* Render and control web pages
*/
interface WebContents extends EventEmitter {
/** Loads the url in the window */
loadURL(url: string, options?: LoadURLOptions): Promise<void>;
/** Loads the given file in the window */
loadFile(filePath: string, options?: LoadFileOptions): Promise<void>;
/** Initiates a download of the resource at url without navigating */
downloadURL(url: string): void;
/** Returns the URL of the current web page */
getURL(): string;
/** Returns the title of the current web page */
getTitle(): string;
/** Returns whether web page is destroyed */
isDestroyed(): boolean;
/** Focuses the web page */
focus(): void;
/** Returns whether the web page is focused */
isFocused(): boolean;
/** Returns whether the web page is loading */
isLoading(): boolean;
/** Returns whether the web page is waiting for a first-response from the main resource */
isLoadingMainFrame(): boolean;
/** Returns whether the web page is waiting for a first-response for the main resource of the page */
isWaitingForResponse(): boolean;
/** Stops any pending navigation */
stop(): void;
/** Reloads the current web page */
reload(): void;
/** Reloads current page and ignores cache */
reloadIgnoringCache(): void;
/** Returns whether the renderer process has crashed */
isCrashed(): boolean;
/** Forcefully terminates the renderer process */
forcefullyCrashRenderer(): void;
/** Returns the user agent for this web page */
getUserAgent(): string;
/** Overrides the user agent for this web page */
setUserAgent(userAgent: string): void;
/** Injects CSS into the current web page */
insertCSS(css: string, options?: InsertCSSOptions): Promise<string>;
/** Removes the inserted CSS from the current web page */
removeInsertedCSS(key: string): Promise<void>;
/** Evaluates code in page */
executeJavaScript(code: string, userGesture?: boolean): Promise<any>;
/** Ignores application menu shortcuts while this web contents is focused */
setIgnoreMenuShortcuts(ignore: boolean): void;
/** Mute audio on the current web page */
setAudioMuted(muted: boolean): void;
/** Returns whether this page is muted */
isAudioMuted(): boolean;
/** Returns whether this page is currently audible */
isCurrentlyAudible(): boolean;
/** Changes the zoom factor to the specified factor */
setZoomFactor(factor: number): void;
/** Returns the current zoom factor */
getZoomFactor(): number;
/** Changes the zoom level to the specified level */
setZoomLevel(level: number): void;
/** Returns the current zoom level */
getZoomLevel(): number;
/** Sets the maximum and minimum pinch-to-zoom level */
setVisualZoomLevelLimits(minimumLevel: number, maximumLevel: number): Promise<void>;
/** Returns the operating system pid of the associated renderer process */
getOSProcessId(): number;
/** Returns the Chromium internal pid of the associated renderer */
getProcessId(): number;
/** Takes a V8 heap snapshot and saves it to path */
takeHeapSnapshot(path: string): Promise<void>;
/** Starts recording a navigation */
startDrag(item: Item): void;
/** Indicates whether offscreen rendering is enabled */
isOffscreen(): boolean;
/** If offscreen rendering is enabled and not painting, start painting */
startPainting(): void;
/** If offscreen rendering is enabled and painting, stop painting */
stopPainting(): void;
/** If offscreen rendering is enabled returns whether it is currently painting */
isPainting(): boolean;
/** If offscreen rendering is enabled sets the frame rate to the specified number */
setFrameRate(fps: number): void;
/** If offscreen rendering is enabled returns the current frame rate */
getFrameRate(): number;
/** Schedules a full repaint of the window this web contents is in */
invalidate(): void;
/** Returns the WebRTC IP Handling Policy */
getWebRTCIPHandlingPolicy(): string;
/** Setting the WebRTC IP handling policy allows you to control which IPs are exposed via WebRTC */
setWebRTCIPHandlingPolicy(policy: 'default' | 'default_public_interface_only' | 'default_public_and_private_interfaces' | 'disable_non_proxied_udp'): void;
/** Get the system printer list */
getPrintersAsync(): Promise<PrinterInfo[]>;
/** Prints window's web page */
print(options?: WebContentsPrintOptions, callback?: (success: boolean, failureReason: string) => void): void;
/** Prints window's web page as PDF with Chromium's preview printing custom settings */
printToPDF(options: PrintToPDFOptions): Promise<Buffer>;
/** Adds the specified path to DevTools workspace */
addWorkSpace(path: string): void;
/** Removes the specified path from DevTools workspace */
removeWorkSpace(path: string): void;
/** Uses the devtools protocol to send a message to the devtools */
sendInputEvent(inputEvent: MouseInputEvent | MouseWheelInputEvent | KeyboardInputEvent): void;
/** Begin subscribing for presentation events and captured frames */
beginFrameSubscription(onlyDirty: boolean, callback: (image: NativeImage, dirtyRect: Rectangle) => void): void;
/** End subscribing for frame presentations */
endFrameSubscription(): void;
/** Sets the item as dragging item for current drag-drop operation */
startDrag(item: Item): void;
/** Captures a snapshot of the page within the specified rect */
capturePage(rect?: Rectangle): Promise<NativeImage>;
/** Checks if any ServiceWorker is registered and returns a boolean as response to callback */
hasServiceWorker(): Promise<boolean>;
/** Unregisters any ServiceWorker if present and returns a boolean as response to callback when the JS promise is fulfilled or false when the JS promise is rejected */
unregisterServiceWorker(): Promise<boolean>;
/** Send an asynchronous message to renderer process via channel */
send(channel: string, ...args: any[]): void;
/** Sends an input event to the page */
sendInputEvent(event: InputEvent): void;
/** Enable device emulation with the given parameters */
enableDeviceEmulation(parameters: Parameters): void;
/** Disable device emulation enabled by webContents.enableDeviceEmulation */
disableDeviceEmulation(): void;
/** Sends an input event to the page */
postMessage(channel: string, message: any, transfer?: MessagePortMain[]): void;
/** Create a new webContents instance with the given options */
static create(options?: CreateOptions): WebContents;
/** Get all WebContents instances */
static getAllWebContents(): WebContents[];
/** Returns the web contents that is focused in this application */
static getFocusedWebContents(): WebContents | null;
/** Find a WebContents instance according to its ID */
static fromId(id: number): WebContents | null;
/** A Integer property that uniquely identifies this WebContents */
readonly id: number;
/** A Session used by this webContents */
readonly session: Session;
/** A WebContents instance that might own this WebContents */
readonly hostWebContents: WebContents | null;
/** A WebContents of DevTools for this WebContents */
readonly devToolsWebContents: WebContents | null;
/** A Debugger instance for this webContents */
readonly debugger: Debugger;
}Usage Examples:
const { webContents, BrowserWindow } = require('electron');
// Get webContents from a BrowserWindow
const mainWindow = new BrowserWindow();
const contents = mainWindow.webContents;
// Load content
contents.loadURL('https://example.com');
// Execute JavaScript
contents.executeJavaScript(`
console.log('Hello from main process!');
document.title = 'Modified by Electron';
`).then(result => {
console.log('JS execution result:', result);
});
// Send message to renderer
contents.send('main-to-renderer', 'Hello renderer!');
// Handle page events
contents.on('did-finish-load', () => {
console.log('Page finished loading');
});
contents.on('new-window', (event, navigationUrl) => {
// Prevent new window creation
event.preventDefault();
// Open in external browser instead
shell.openExternal(navigationUrl);
});
// Print to PDF
contents.printToPDF({
pageSize: 'A4',
landscape: false
}).then(data => {
fs.writeFileSync('/tmp/print.pdf', data);
});
// Capture page screenshot
contents.capturePage().then(image => {
fs.writeFileSync('/tmp/screenshot.png', image.toPNG());
});New view-based architecture for embedding content within windows.
/**
* View is the basic building block of Electron's View API
*/
class View extends EventEmitter {
/** Create a new View */
constructor();
/** Add a child view */
addChildView(view: View, index?: number): void;
/** Remove a child view */
removeChildView(view: View): void;
/** Set the bounds of this view */
setBounds(bounds: Rectangle): void;
/** Get the bounds of this view */
getBounds(): Rectangle;
/** Set the background color */
setBackgroundColor(color: string): void;
/** A list of child Views */
readonly children: View[];
}
/**
* A WebContentsView can be used to embed web content in a View
*/
class WebContentsView extends View {
/** Create a new WebContentsView */
constructor(options?: WebContentsViewConstructorOptions);
/** The WebContents object owned by this view */
readonly webContents: WebContents;
}
/**
* An ImageView displays image content
*/
class ImageView extends View {
/** Create a new ImageView */
constructor();
/** Set the image content */
setImage(image: NativeImage | null): void;
/** Get the image content */
getImage(): NativeImage | null;
}
/**
* BaseWindow is the base class for BrowserWindow
*/
class BaseWindow extends EventEmitter {
/** Create a new BaseWindow */
constructor(options?: BaseWindowConstructorOptions);
/** Set the content view */
setContentView(view: View): void;
/** Get the content view */
getContentView(): View | null;
/** Shows and gives focus to the window */
show(): void;
/** Hides the window */
hide(): void;
/** Closes the window */
close(): void;
/** Returns whether the window is destroyed */
isDestroyed(): boolean;
/** Set the bounds of the window */
setBounds(bounds: Partial<Rectangle>, animate?: boolean): void;
/** Get the bounds of the window */
getBounds(): Rectangle;
/** A integer representing the unique ID of the window */
readonly id: number;
}Usage Examples:
const { BaseWindow, WebContentsView, ImageView } = require('electron');
// Create a base window with views
const win = new BaseWindow({
width: 800,
height: 600
});
// Create a web contents view
const webView = new WebContentsView({
webPreferences: {
nodeIntegration: false,
contextIsolation: true
}
});
webView.webContents.loadURL('https://electronjs.org');
webView.setBounds({ x: 0, y: 0, width: 400, height: 600 });
// Create an image view
const imageView = new ImageView();
const image = nativeImage.createFromPath('/path/to/image.png');
imageView.setImage(image);
imageView.setBounds({ x: 400, y: 0, width: 400, height: 300 });
// Add views to window
win.contentView.addChildView(webView);
win.contentView.addChildView(imageView);
win.show();interface LoadURLOptions {
httpReferrer?: string | Referrer;
userAgent?: string;
extraHeaders?: string;
postData?: PostData[];
baseURLForDataURL?: string;
}
interface LoadFileOptions {
query?: Record<string, string>;
search?: string;
hash?: string;
}
interface OpenDevToolsOptions {
mode?: 'right' | 'bottom' | 'undocked' | 'detach';
activate?: boolean;
}
interface InsertCSSOptions {
cssOrigin?: 'author' | 'user';
}
interface PrinterInfo {
name: string;
displayName: string;
description: string;
status: number;
isDefault: boolean;
options?: Record<string, string>;
}
interface WebContentsViewConstructorOptions {
webPreferences?: WebPreferences;
}
interface BaseWindowConstructorOptions {
show?: boolean;
frame?: boolean;
parent?: BaseWindow;
modal?: boolean;
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;
skipTaskbar?: boolean;
kiosk?: boolean;
title?: string;
icon?: NativeImage | string;
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';
trafficLightPosition?: Point;
roundedCorners?: boolean;
thickFrame?: boolean;
vibrancy?: string;
zoomToPageWidth?: boolean;
tabbingIdentifier?: string;
}
interface CreateOptions {
nodeIntegration?: boolean;
nodeIntegrationInWorker?: boolean;
preload?: string;
sandbox?: boolean;
contextIsolation?: boolean;
webSecurity?: boolean;
enableRemoteModule?: boolean;
images?: boolean;
webAudio?: boolean;
plugins?: boolean;
experimentalFeatures?: boolean;
scrollBounce?: boolean;
blinkFeatures?: string;
disableBlinkFeatures?: string;
defaultFontFamily?: Record<string, string>;
defaultFontSize?: number;
defaultMonospaceFontSize?: number;
minimumFontSize?: number;
defaultEncoding?: string;
backgroundThrottling?: boolean;
offscreen?: boolean;
webgl?: boolean;
navigateOnDragDrop?: boolean;
autoplayPolicy?: string;
enableWebSQL?: boolean;
spellcheck?: boolean;
}
interface InputEvent {
type: 'mouseDown' | 'mouseUp' | 'mouseMove' | 'mouseWheel' | 'mouseEnter' | 'mouseLeave' | 'contextMenu' | 'keyDown' | 'keyUp' | 'char';
modifiers?: Array<'shift' | 'control' | 'alt' | 'meta' | 'isKeypad' | 'isAutoRepeat' | 'leftButtonDown' | 'middleButtonDown' | 'rightButtonDown' | 'capsLock' | 'numLock' | 'left' | 'right'>;
}
interface Parameters {
screenPosition: 'desktop' | 'mobile';
screenSize: Size;
viewPosition: Point;
deviceScaleFactor: number;
viewSize: Size;
scale: number;
}