### Install webviewjs via NPM
Source: https://github.com/webviewjs/webview/blob/main/docs/getting-started/installation.md
Installs the webviewjs package using npm. Ensure Node.js and npm are installed.
```bash
npm install @webviewjs/webview
```
--------------------------------
### Install Dependencies with Bun
Source: https://github.com/webviewjs/webview/blob/main/README.md
Install project dependencies using Bun. Ensure Bun is installed and the version meets the prerequisites.
```bash
bun install
```
--------------------------------
### Install WebKitGTK and Development Headers
Source: https://github.com/webviewjs/webview/blob/main/docs/platform/linux.md
Install the necessary runtime and development headers for WebKitGTK on Debian/Ubuntu, Fedora/RHEL, or Arch Linux systems.
```bash
sudo apt install libwebkit2gtk-4.1-dev libxdo-dev
```
```bash
sudo dnf install webkit2gtk4.1-devel libxdo-devel
```
```bash
sudo pacman -S webkit2gtk-4.1 xdotool
```
--------------------------------
### Install Linux Dependencies
Source: https://github.com/webviewjs/webview/blob/main/docs/getting-started/installation.md
Installs necessary development libraries for webviewjs on Debian/Ubuntu, Fedora, or Arch Linux.
```bash
# Debian / Ubuntu
sudo apt install libwebkit2gtk-4.1-dev libxdo-dev
```
```bash
# Fedora
sudo dnf install webkit2gtk4.1-devel libxdo-devel
```
```bash
# Arch
sudo pacman -S webkit2gtk-4.1 xdotool
```
--------------------------------
### Build webviewjs from Source
Source: https://github.com/webviewjs/webview/blob/main/docs/getting-started/installation.md
Clones the webviewjs repository, installs dependencies, and builds the project. Requires Rust toolchain and napi-rs CLI.
```bash
git clone https://github.com/webviewjs/webview
cd webview
npm install
npm run build # compiles Rust and generates JS bindings
```
--------------------------------
### Basic Menu Setup in WebviewJS
Source: https://github.com/webviewjs/webview/blob/main/README.md
Sets up a global application menu with File and Edit submenus. This is useful for defining the primary navigation and actions available to the user across the application.
```javascript
import { Application } from '@webviewjs/webview';
const app = new Application();
// Set global application menu
app.setMenu({
items: [
{
label: 'File',
submenu: {
items: [
{ id: 'new', label: 'New', accelerator: 'CmdOrCtrl+N' },
{ id: 'open', label: 'Open', accelerator: 'CmdOrCtrl+O' },
{ role: 'separator' },
{ id: 'quit', label: 'Quit', accelerator: 'CmdOrCtrl+Q' },
],
},
},
{
label: 'Edit',
submenu: {
items: [{ role: 'copy' }, { role: 'paste' }, { role: 'cut' }, { role: 'selectall' }],
},
},
],
});
const window = app.createBrowserWindow();
const webview = window.createWebview({ url: 'https://nodejs.org' });
app.run();
```
--------------------------------
### Accelerator Syntax Examples
Source: https://github.com/webviewjs/webview/blob/main/docs/api/menu.md
Illustrates the syntax for defining keyboard shortcuts (accelerators) for menu items, including platform-specific modifiers.
```plaintext
CmdOrCtrl+S → Cmd+S on macOS, Ctrl+S elsewhere
Alt+F4
Shift+CmdOrCtrl+Z
F5
```
--------------------------------
### Basic Menu Setup
Source: https://github.com/webviewjs/webview/blob/main/docs/guides/menus.md
Set up the main application menu with File and Edit submenus. Handle custom menu clicks by listening for `CustomMenuClick` events and performing actions based on the clicked item's ID.
```js
import { Application, WebviewApplicationEvent } from '@webviewjs/webview';
const app = new Application();
app.setMenu({
items: [
{
label: 'File',
submenu: {
items: [
{ id: 'new', label: 'New', accelerator: 'CmdOrCtrl+N' },
{ id: 'open', label: 'Open', accelerator: 'CmdOrCtrl+O' },
{ role: 'separator' },
{ role: 'quit' },
],
},
},
{
label: 'Edit',
submenu: {
items: [
{ role: 'undo' }, { role: 'redo' }, { role: 'separator' },
{ role: 'cut' }, { role: 'copy' }, { role: 'paste' },
],
},
},
],
});
app.onEvent((ev) => {
if (ev.event === WebviewApplicationEvent.CustomMenuClick) {
switch (ev.customMenuEvent.id) {
case 'new': createNewWindow(); break;
case 'open': openFilePicker(); break;
}
}
});
```
--------------------------------
### run(options?)
Source: https://github.com/webviewjs/webview/blob/main/docs/api/application.md
Starts the application's event pump, processing OS events at a set interval. This method returns immediately.
```APIDOC
## `run(options?)`
Start the event pump. Calls `pumpEvents()` on a `setInterval` and returns immediately.
```ts
app.run(options?: { interval?: number; ref?: boolean }): void
```
| Option | Default |
|---|---|
| `interval` | `16` | Pump interval in ms |
| `ref` | `true` | If `false` the timer won't prevent process exit |
```
--------------------------------
### Window Menu Configuration
Source: https://github.com/webviewjs/webview/blob/main/docs/api/browser-window.md
Sets the window's menu. Refer to the Menus guide for more details.
```typescript
win.setMenu(options: MenuOptions | null): void
```
--------------------------------
### setMenu(options?)
Source: https://github.com/webviewjs/webview/blob/main/docs/api/application.md
Sets the global application menu. Pass `null` to remove the existing menu. Refer to the Menus guide for the full options structure.
```APIDOC
## `setMenu(options?)`
Set the global application menu. Pass `null` to remove it.
```ts
app.setMenu(options?: MenuOptions): void
```
See [Menus guide](../guides/menus.md) for the full options shape.
```
--------------------------------
### Get WebView2 Version
Source: https://github.com/webviewjs/webview/blob/main/docs/platform/windows.md
Retrieves the version of the installed WebView2 runtime. This is useful for debugging or ensuring compatibility.
```javascript
import { getWebviewVersion } from '@webviewjs/webview';
console.log(getWebviewVersion()); // e.g. "128.0.2739.42"
```
--------------------------------
### Register a Custom Protocol Handler
Source: https://github.com/webviewjs/webview/blob/main/docs/guides/custom-protocols.md
Register a protocol handler for a custom scheme before creating a webview. This example handles 'app://' URLs by serving files from the 'dist' directory.
```javascript
import { readFile } from 'node:fs/promises';
import { extname, join } from 'node:path';
import { Application } from '@webviewjs/webview';
const MIME = {
'.html': 'text/html; charset=utf-8',
'.js': 'application/javascript; charset=utf-8',
'.css': 'text/css',
};
const app = new Application();
const win = app.createBrowserWindow();
win.registerProtocol('app', async (request) => {
const url = new URL(request.url);
const path = join(process.cwd(), 'dist', url.pathname);
try {
return {
statusCode: 200,
body: await readFile(path),
mimeType: MIME[extname(path)] ?? 'application/octet-stream',
};
} catch {
return {
statusCode: 404,
body: Buffer.from(`Not found: ${url.pathname}`),
mimeType: 'text/plain; charset=utf-8',
};
}
});
win.createWebview({ url: 'app://localhost/index.html' });
app.run();
```
--------------------------------
### Update Menu at Runtime
Source: https://github.com/webviewjs/webview/blob/main/docs/guides/menus.md
Modify the application menu dynamically after initial setup. You can replace the entire menu structure with new items or remove the menu completely by setting it to null.
```js
// Replace the whole menu
app.setMenu({ items: updatedItems });
// Remove entirely
app.setMenu(null);
```
--------------------------------
### Window Size and Position
Source: https://github.com/webviewjs/webview/blob/main/docs/api/browser-window.md
Methods to get and set the inner (content) size and outer size (including decorations) of the window, as well as its position on the screen. Also includes methods to get the device-pixel ratio.
```typescript
// Inner (content) size in logical pixels
win.getSize(): Dimensions // { width, height }
win.getOuterSize(): Dimensions // includes decorations
win.setSize(width: number, height: number): void
win.setMinSize(width: number | null, height: number | null): void
win.setMaxSize(width: number | null, height: number | null): void
// Position of the outer window in physical pixels
win.getPosition(): Position | null // { x, y }
win.setPosition(x: number, y: number): void
win.center(): void // center on current monitor
win.scaleFactor(): number // device-pixel ratio
```
--------------------------------
### Size & Position
Source: https://github.com/webviewjs/webview/blob/main/docs/api/browser-window.md
Methods for getting and setting the window's inner and outer dimensions, as well as its position on the screen.
```APIDOC
## Size & position
```ts
// Inner (content) size in logical pixels
win.getSize(): Dimensions // { width, height }
win.getOuterSize(): Dimensions // includes decorations
win.setSize(width: number, height: number): void
win.setMinSize(width: number | null, height: number | null): void
win.setMaxSize(width: number | null, height: number | null): void
// Position of the outer window in physical pixels
win.getPosition(): Position | null // { x, y }
win.setPosition(x: number, y: number): void
win.center(): void // center on current monitor
win.scaleFactor(): number // device-pixel ratio
```
```
--------------------------------
### Bounds (Child Webviews)
Source: https://github.com/webviewjs/webview/blob/main/docs/api/webview.md
Methods for getting and setting the bounds of child webviews.
```APIDOC
## Bounds Methods (Child Webviews)
### `getBounds(): WebviewBounds | null`
Returns the current bounds (position and size) of the child webview, or null if not applicable.
### `setBounds(bounds: WebviewBounds): void`
Sets the bounds (position and size) of the child webview.
```
```APIDOC
## WebviewBounds
Interface for defining the bounds of a webview.
### Properties
- **x** (number) - Required - The x-coordinate of the top-left corner.
- **y** (number) - Required - The y-coordinate of the top-left corner.
- **width** (number) - Required - The width of the webview.
- **height** (number) - Required - The height of the webview.
```
--------------------------------
### Webview Bounds Management
Source: https://github.com/webviewjs/webview/blob/main/docs/api/webview.md
Allows getting and setting the position and dimensions of a child webview at runtime.
```typescript
webview.getBounds(): WebviewBounds | null
webview.setBounds(bounds: WebviewBounds): void
```
--------------------------------
### Set Global Application Menu
Source: https://github.com/webviewjs/webview/blob/main/docs/api/application.md
Sets the global menu for the application. Pass `null` to remove the existing menu. Refer to the Menus guide for the full options shape.
```typescript
app.setMenu(options?: MenuOptions): void
```
--------------------------------
### Run Application Event Pump
Source: https://github.com/webviewjs/webview/blob/main/docs/api/application.md
Starts the application's event pump, which processes OS events at a specified interval. The `ref` option controls whether the timer prevents the process from exiting.
```typescript
app.run(options?: { interval?: number; ref?: boolean }): void
```
--------------------------------
### Manual Event Loop Control in WebviewJS
Source: https://github.com/webviewjs/webview/blob/main/docs/getting-started/event-loop.md
This example demonstrates how to manually control the event loop after stopping the interval with `app.stop()`. It shows processing events in a tight loop for CPU-intensive tasks before resuming the standard interval-based loop with `app.run()`.
```javascript
app.stop();
// run a tight loop for a CPU-intensive frame:
while (frames-- > 0) app.pumpEvents();
app.run(); // hand back to the interval
```
--------------------------------
### Application Constructor
Source: https://github.com/webviewjs/webview/blob/main/docs/api/application.md
Initializes a new Application instance. Options are accepted but currently unused.
```APIDOC
## Constructor
```ts
new Application(options?: ApplicationOptions)
```
`ApplicationOptions` is accepted but currently unused; pass `null` or omit it.
```
--------------------------------
### createBrowserWindow(options?)
Source: https://github.com/webviewjs/webview/blob/main/docs/api/application.md
Creates and returns a new `BrowserWindow` instance. Refer to the `BrowserWindow` documentation for available options.
```APIDOC
## `createBrowserWindow(options?)`
Create and return a new [`BrowserWindow`](./browser-window.md).
```ts
app.createBrowserWindow(options?: BrowserWindowOptions): BrowserWindow
```
```
--------------------------------
### Import and Instantiate Application
Source: https://github.com/webviewjs/webview/blob/main/docs/api/application.md
Import the Application class and create a new instance. This is the first step in setting up your webviewjs application.
```javascript
import { Application } from '@webviewjs/webview';
const app = new Application();
```
--------------------------------
### Application Resource Management with `using`
Source: https://github.com/webviewjs/webview/blob/main/docs/api/application.md
Demonstrates using the `using` statement for explicit resource management, ensuring that `app.exit()` is called automatically upon exiting the scope.
```javascript
{
using app = new Application();
// …
} // app.exit() called automatically
```
--------------------------------
### Build Project with Bun
Source: https://github.com/webviewjs/webview/blob/main/README.md
Build the project using the 'build' script defined in package.json with Bun. This command is used during development.
```bash
bun run build
```
--------------------------------
### Create a Webview
Source: https://github.com/webviewjs/webview/blob/main/docs/api/browser-window.md
Attaches a webview to the window. Returns a Webview object.
```typescript
win.createWebview(options?: WebviewOptions): Webview
```
--------------------------------
### Create Webview
Source: https://github.com/webviewjs/webview/blob/main/docs/api/browser-window.md
Attaches a webview to the window and returns a Webview object.
```APIDOC
## createWebview(options?)
Attach a webview to the window. Returns a [`Webview`](./webview.md).
```ts
win.createWebview(options?: WebviewOptions): Webview
```
```
--------------------------------
### Build WebviewJS Executable
Source: https://github.com/webviewjs/webview/blob/main/README.md
Use this command to build a single executable application from your JavaScript script. Specify input script, output directory, and application name.
```bash
webview --build --input ./path/to/your/script.js --output ./path/to/output-directory --name my-app
```
--------------------------------
### Webview Creation Options
Source: https://github.com/webviewjs/webview/blob/main/docs/api/webview.md
Options available when creating a new webview instance.
```APIDOC
## WebviewOptions
Interface for configuring a new webview.
### Properties
- **url** (string) - Optional - URL to load on start.
- **html** (string) - Optional - Inline HTML to render (mutually exclusive with url).
- **x** (number) - Optional - Left offset in logical pixels (child webviews only).
- **y** (number) - Optional - Top offset in logical pixels (child webviews only).
- **width** (number) - Optional - Width in logical pixels (child webviews only).
- **height** (number) - Optional - Height in logical pixels (child webviews only).
- **child** (boolean) - Optional - If true, position is relative to parent window.
- **enableDevtools** (boolean) - Optional - Enable DevTools.
- **transparent** (boolean) - Optional - Transparent background.
- **incognito** (boolean) - Optional - Private mode (no persistent storage).
- **userAgent** (string) - Optional - Custom user-agent string.
- **preload** (string) - Optional - JS injected before any page script runs.
- **ipcName** (string) - Optional - Alias for window.ipc, for example window.bindings.
```
--------------------------------
### Create a Minimal WebviewJS Application
Source: https://github.com/webviewjs/webview/blob/main/docs/getting-started/quick-start.md
This snippet shows how to create a basic WebviewJS application with a browser window and a webview pointing to a remote URL. It requires importing Application and BrowserWindow from '@webviewjs/webview'.
```javascript
import { Application, BrowserWindow } from '@webviewjs/webview';
const app = new Application();
const win = app.createBrowserWindow({
title: 'My App',
width: 1024,
height: 768,
});
const webview = win.createWebview({ url: 'https://example.com' });
app.run();
```
--------------------------------
### Nested Submenus
Source: https://github.com/webviewjs/webview/blob/main/docs/guides/menus.md
Create complex menu structures by nesting submenus within other menu items. This example demonstrates a 'View' menu with a 'Zoom' submenu containing zoom in, zoom out, and reset options.
```js
{
label: 'View',
submenu: {
items: [
{
label: 'Zoom',
submenu: {
items: [
{ id: 'zoom-in', label: 'Zoom In', accelerator: 'CmdOrCtrl+=' },
{ id: 'zoom-out', label: 'Zoom Out', accelerator: 'CmdOrCtrl+-' },
{ id: 'zoom-reset', label: 'Reset', accelerator: 'CmdOrCtrl+0' },
],
},
},
{ role: 'fullscreen' },
],
},
}
```
--------------------------------
### IPC Communication Between Webview and Main Process
Source: https://github.com/webviewjs/webview/blob/main/README.md
Demonstrates setting up IPC handlers for sending messages from the webview to the main process and receiving replies. Ensure the preload script is correctly configured to handle messages.
```javascript
const app = new Application();
const window = app.createBrowserWindow();
const webview = window.createWebview({
html: `
Webview
Hello world!
`,
preload: `window.onIpcMessage = function(data) {
const output = document.getElementById('output');
output.innerText = `Server Sent A Message: ${data}`;
}`,
});
if (!webview.isDevtoolsOpen()) webview.openDevtools();
webview.onIpcMessage((data) => {
const reply = `You sent ${data.body.toString('utf-8')}`;
webview.evaluateScript(`onIpcMessage("${reply}")`);
});
app.run();
```
--------------------------------
### Menu
Source: https://github.com/webviewjs/webview/blob/main/docs/api/browser-window.md
Method for setting the window's menu.
```APIDOC
## Menu
```ts
win.setMenu(options: MenuOptions | null): void
```
See [Menus guide](../guides/menus.md).
```
--------------------------------
### Create Browser Window
Source: https://github.com/webviewjs/webview/blob/main/docs/api/application.md
Creates and returns a new `BrowserWindow` instance. Options can be provided to configure the new window.
```typescript
app.createBrowserWindow(options?: BrowserWindowOptions): BrowserWindow
```
--------------------------------
### Theme
Source: https://github.com/webviewjs/webview/blob/main/docs/api/browser-window.md
Method for setting the window's theme to light, dark, or system default.
```APIDOC
## Theme
```ts
win.setTheme(theme: Theme | null): void // 'Light' | 'Dark' | null (system)
```
```
--------------------------------
### Load External URL with WebviewJS
Source: https://github.com/webviewjs/webview/blob/main/README.md
Demonstrates how to create a browser window and load an external URL using WebviewJS. Supports both ES module and CommonJS import styles.
```javascript
import { Application } from '@webviewjs/webview';
// or
const { Application } = require('@webviewjs/webview');
const app = new Application();
const window = app.createBrowserWindow();
const webview = window.createWebview();
webview.loadUrl('https://nodejs.org');
app.run();
```
--------------------------------
### Register Multiple Custom Protocols
Source: https://github.com/webviewjs/webview/blob/main/docs/guides/custom-protocols.md
Demonstrates registering multiple custom protocol handlers for different schemes, such as 'app' and 'api', before creating a webview.
```javascript
win.registerProtocol('app', appHandler);
win.registerProtocol('api', async (request) => {
const response = await fetch(`https://example.test${new URL(request.url).pathname}`);
return {
statusCode: response.status,
body: Buffer.from(await response.arrayBuffer()),
mimeType: response.headers.get('content-type') ?? 'application/octet-stream',
};
});
```
--------------------------------
### Window Theming
Source: https://github.com/webviewjs/webview/blob/main/docs/api/browser-window.md
Sets the window's theme to 'Light', 'Dark', or null to follow the system's theme.
```typescript
win.setTheme(theme: Theme | null): void // 'Light' | 'Dark' | null (system)
```
--------------------------------
### Icon & Progress
Source: https://github.com/webviewjs/webview/blob/main/docs/api/browser-window.md
Methods for setting the window icon and displaying a progress bar on the window.
```APIDOC
## Icon & progress
```ts
win.setWindowIcon(rgba: Buffer, width: number, height: number): void
win.setProgressBar(progress: JsProgressBar): void
```
`JsProgressBar`:
```ts
interface JsProgressBar {
state?: ProgressBarState; // 'None' | 'Normal' | 'Indeterminate' | 'Paused' | 'Error'
progress?: number; // 0-100
}
```
```
--------------------------------
### Track Windows with a Map
Source: https://github.com/webviewjs/webview/blob/main/docs/guides/multiple-windows.md
Manages multiple windows using a Map to store and retrieve them by ID. Includes logic for showing existing windows or creating new ones. Also demonstrates handling window close and application close events.
```javascript
const windows = new Map(); // id → BrowserWindow
function openWindow(id, url) {
if (windows.has(id)) {
windows.get(id).show();
return;
}
const win = app.createBrowserWindow({ title: id });
win.createWebview({ url });
windows.set(id, win);
}
app.onEvent((ev) => {
if (ev.event === WebviewApplicationEvent.WindowCloseRequested) {
// The window has been hidden by the runtime.
// Remove it from your map if you track open state.
}
if (ev.event === WebviewApplicationEvent.ApplicationCloseRequested) {
// All windows closed — shut down.
app.exit();
}
});
```
--------------------------------
### Decorations & Behaviour
Source: https://github.com/webviewjs/webview/blob/main/docs/api/browser-window.md
Methods for customizing window decorations and behavior, such as resizability, minimizability, maximizability, closability, always-on-top, content protection, workspace visibility, window level, and taskbar skipping.
```APIDOC
## Decorations & behaviour
```ts
win.setResizable(resizable: boolean): void
win.setMinimizable(minimizable: boolean): void
win.setMaximizable(maximizable: boolean): void
win.setClosable(closable: boolean): void
win.setAlwaysOnTop(always: boolean): void
win.setContentProtection(enabled: boolean): void
win.setVisibleOnAllWorkspaces(visible: boolean): void
win.setDecorations(decorated: boolean): void
win.setWindowLevel(level: WindowLevel): void
win.setSkipTaskbar(skip: boolean): void // Windows only
```
```
--------------------------------
### Node to Page with Callback
Source: https://github.com/webviewjs/webview/blob/main/docs/guides/ipc-messaging.md
Demonstrates executing a script in the web page and receiving a serialized JavaScript result back in Node.js using `webview.evaluateScriptWithCallback()`.
```javascript
webview.evaluateScriptWithCallback('document.title', (error, title) => {
if (error) throw error;
console.log(title);
});
```
--------------------------------
### Window State Management
Source: https://github.com/webviewjs/webview/blob/main/docs/api/browser-window.md
Methods for managing the window's title, visibility, and state (minimized, maximized, fullscreen, focus).
```APIDOC
## Window state
```ts
win.setTitle(title: string): void
win.setVisible(visible: boolean): void
win.show(): void
win.hide(): void
win.minimize(): void
win.maximize(): void
win.unmaximize(): void
win.setFullscreen(type: FullscreenType | null): void
win.focus(): void
win.requestRedraw(): void
```
```
--------------------------------
### Graceful Application Closing and Resource Cleanup
Source: https://github.com/webviewjs/webview/blob/main/README.md
Shows how to bind to application events to perform cleanup when the application or windows are requested to close. This ensures all resources are properly released.
```javascript
const app = new Application();
const window = app.createBrowserWindow();
const webview = window.createWebview({ url: 'https://nodejs.org' });
// Set up event handler for close events
// You can use either onEvent() or bind() - they are equivalent
app.bind((event) => {
if (event.event === WebviewApplicationEvent.ApplicationCloseRequested) {
console.log('Application is closing, cleaning up resources...');
// Perform cleanup here: save data, close connections, etc.
}
if (event.event === WebviewApplicationEvent.WindowCloseRequested) {
console.log('Window close requested');
// Perform window-specific cleanup
}
});
// Close the application gracefully (cleans up temp folders)
app.exit();
// Or hide/show the window
window.hide(); // Hide the window
window.show(); // Show the window again
// Or reload the webview
webview.reload();
```
--------------------------------
### Custom Protocols
Source: https://github.com/webviewjs/webview/blob/main/docs/api/browser-window.md
Registers a URL-scheme handler. This must be called before `createWebview()`.
```APIDOC
## Custom protocols
Register a URL-scheme handler before creating the webview. Must be called before `createWebview()`.
```ts
win.registerProtocol(
name: string,
handler: (request: CustomProtocolRequest) =>
CustomProtocolResponse | Promise
): void
```
The handler may perform asynchronous file, database, or network work. See [Custom Protocols guide](../guides/custom-protocols.md).
```
--------------------------------
### Register and Use Custom URL Protocol
Source: https://github.com/webviewjs/webview/blob/main/README.md
Shows how to register a custom URL protocol handler in Node.js to serve local files. The webview can then navigate to URLs using this custom protocol.
```javascript
window.registerProtocol('app', async (request) => {
const filePath = join(process.cwd(), 'dist', new URL(request.url).pathname);
try {
return { body: await readFile(filePath), mimeType: 'text/html; charset=utf-8' };
} catch {
return { statusCode: 404, body: Buffer.from('Not found'), mimeType: 'text/plain' };
}
});
window.createWebview({ url: 'app://localhost/index.html' });
```
--------------------------------
### Setting a Global Menu
Source: https://github.com/webviewjs/webview/blob/main/docs/api/menu.md
Sets a global menu bar for the application. This menu will be displayed for all windows unless overridden by a per-window menu.
```APIDOC
## Setting a Global Menu
### Description
Sets a global menu bar for the application. This menu will be displayed for all windows unless overridden by a per-window menu.
### Method
`app.setMenu(options)`
### Parameters
#### Request Body
- **options** (object) - Required - An object conforming to `MenuOptions` that defines the menu structure.
### Request Example
```js
app.setMenu({
items: [
{
label: 'File',
submenu: {
items: [
{ label: 'New', id: 'file-new', accelerator: 'CmdOrCtrl+N' },
{ label: 'Open', id: 'file-open', accelerator: 'CmdOrCtrl+O' },
{ role: 'separator' },
{ role: 'quit' },
],
},
},
{
label: 'Edit',
submenu: {
items: [
{ role: 'undo' },
{ role: 'redo' },
{ role: 'separator' },
{ role: 'cut' },
{ role: 'copy' },
{ role: 'paste' },
{ role: 'selectall' },
],
},
},
],
});
```
### Notes
- Calling `setMenu()` again replaces the existing menu.
- Pass `null` to remove the global menu.
```
--------------------------------
### Appearance
Source: https://github.com/webviewjs/webview/blob/main/docs/api/webview.md
Method for setting the background color of the webview.
```APIDOC
## `setBackgroundColor(r: number, g: number, b: number, a: number): void`
Sets the background color of the webview using RGBA values (0-255 for each component).
```
--------------------------------
### Window Decorations and Behavior
Source: https://github.com/webviewjs/webview/blob/main/docs/api/browser-window.md
Control window behavior and appearance, including resizability, minimizability, maximizability, closability, always-on-top status, content protection, visibility across workspaces, window level, and taskbar skipping.
```typescript
win.setResizable(resizable: boolean): void
win.setMinimizable(minimizable: boolean): void
win.setMaximizable(maximizable: boolean): void
win.setClosable(closable: boolean): void
win.setAlwaysOnTop(always: boolean): void
win.setContentProtection(enabled: boolean): void
win.setVisibleOnAllWorkspaces(visible: boolean): void
win.setDecorations(decorated: boolean): void
win.setWindowLevel(level: WindowLevel): void
win.setSkipTaskbar(skip: boolean): void // Windows only
```
--------------------------------
### Expose Native Functions to Webview
Source: https://github.com/webviewjs/webview/blob/main/README.md
Demonstrates how to expose a JavaScript namespace from Node.js to the webview, allowing the webview to call native functions asynchronously. All exposed values, arguments, and results must be JSON-serializable.
```javascript
webview.expose('native', {
version: '0.1.4',
readConfig: async () => JSON.parse(await readFile('./config.json', 'utf8')),
});
```
```javascript
console.log(window.native.version);
const config = await window.native.readConfig();
```
--------------------------------
### BrowserWindow Options Interface
Source: https://github.com/webviewjs/webview/blob/main/docs/api/browser-window.md
Defines the configuration options for creating a new BrowserWindow. These options control various aspects of the window's appearance and behavior.
```typescript
interface BrowserWindowOptions {
title?: string; // default: "WebviewJS"
width?: number; // default: 800 (physical px)
height?: number; // default: 600 (physical px)
x?: number; // initial left position (logical px)
y?: number; // initial top position (logical px)
resizable?: boolean; // default: true
visible?: boolean; // default: true
decorations?: boolean; // default: true (title bar + border)
transparent?: boolean; // default: false
maximized?: boolean; // default: false
maximizable?: boolean; // default: true
minimizable?: boolean; // default: true
focused?: boolean; // default: true
alwaysOnTop?: boolean; // default: false
alwaysOnBottom?: boolean;
contentProtection?: boolean;
visibleOnAllWorkspaces?: boolean;
fullscreen?: FullscreenType; // 'Exclusive' | 'Borderless'
menu?: MenuOptions; // per-window menu (overrides global)
showMenu?: boolean; // show the global menu on this window
}
```
--------------------------------
### Implement IPC for Webview to Node Communication
Source: https://github.com/webviewjs/webview/blob/main/docs/getting-started/quick-start.md
Shows how to send messages from the webview to the Node.js backend using `window.ipc.postMessage` and how the backend can respond by evaluating JavaScript in the webview. This is useful for triggering actions or updating the UI based on user interaction.
```javascript
const webview = win.createWebview({
html: '
',
});
webview.onIpcMessage((msg) => {
console.log('IPC body:', msg.body.toString());
webview.evaluateScript('document.body.style.background = "lime"');
});
```
--------------------------------
### WebviewOptions.ipcName
Source: https://github.com/webviewjs/webview/blob/main/docs/api/types.md
Allows aliasing `window.ipc` for easier access in page scripts.
```APIDOC
## `WebviewOptions.ipcName`
`ipcName?: string` adds a page-global alias for wry's built-in `window.ipc`. For example, `{ ipcName: 'bindings' }` makes `window.bindings.postMessage(...)` available before page scripts run. `window.ipc` remains available.
```
--------------------------------
### DevTools
Source: https://github.com/webviewjs/webview/blob/main/docs/api/webview.md
Methods for managing the webview's Developer Tools.
```APIDOC
## DevTools Methods
### `openDevtools(): void`
Opens the Developer Tools for the webview.
### `closeDevtools(): void`
Closes the Developer Tools for the webview.
### `isDevtoolsOpen(): boolean`
Returns true if the Developer Tools are currently open, false otherwise.
```
--------------------------------
### Load Local HTML Content in Webview
Source: https://github.com/webviewjs/webview/blob/main/docs/getting-started/quick-start.md
Demonstrates how to load local HTML content directly into a webview instead of a remote URL. This is useful for displaying static UI elements or locally hosted applications.
```javascript
const webview = win.createWebview({
html: '
Hello from WebviewJS
',
});
```
--------------------------------
### Webview Options Interface
Source: https://github.com/webviewjs/webview/blob/main/docs/api/webview.md
Defines the configuration options available when creating a new webview. These options control aspects like the initial URL or HTML, positioning, size, and feature enablement.
```typescript
interface WebviewOptions {
url?: string; // URL to load on start
html?: string; // Inline HTML to render (mutually exclusive with url)
x?: number; // Left offset in logical pixels (child webviews only)
y?: number; // Top offset in logical pixels (child webviews only)
width?: number; // Width in logical pixels (child webviews only)
height?: number; // Height in logical pixels (child webviews only)
child?: boolean; // If true, position is relative to parent window
enableDevtools?: boolean; // Enable DevTools
transparent?: boolean; // Transparent background
incognito?: boolean; // Private mode (no persistent storage)
userAgent?: string; // Custom user-agent string
preload?: string; // JS injected before any page script runs
ipcName?: string; // Alias for window.ipc, for example window.bindings
}
```
--------------------------------
### File Dialogs
Source: https://github.com/webviewjs/webview/blob/main/docs/api/browser-window.md
Opens a file dialog to allow the user to select files.
```APIDOC
## File dialogs
```ts
win.openFileDialog(options?: FileDialogOptions): Promise
```
```ts
interface FileDialogOptions {
multiple?: boolean;
title?: string;
defaultPath?: string;
filters?: Array<{ name: string; extensions: string[] }>;
}
```
```
--------------------------------
### Create Transparent and Frameless Window on macOS
Source: https://github.com/webviewjs/webview/blob/main/docs/platform/macos.md
Create a browser window with transparency and no window decorations. This allows for custom UI elements and overlays.
```javascript
const win = app.createBrowserWindow({ transparent: true, decorations: false });
```
--------------------------------
### Handle WebviewJS Window and Application Events
Source: https://github.com/webviewjs/webview/blob/main/docs/getting-started/quick-start.md
This snippet illustrates how to react to various events emitted by the WebviewJS application and its windows. It includes handling window close requests and application exit events.
```javascript
app.onEvent((event) => {
switch (event.event) {
case WebviewApplicationEvent.WindowCloseRequested:
console.log('A window was closed');
break;
case WebviewApplicationEvent.ApplicationCloseRequested:
console.log('All windows closed — exiting');
app.exit();
break;
case WebviewApplicationEvent.CustomMenuClick:
console.log('Menu item clicked:', event.customMenuEvent?.id);
break;
}
});
```
--------------------------------
### Webview Navigation Methods
Source: https://github.com/webviewjs/webview/blob/main/docs/api/webview.md
Provides methods for controlling the navigation of the webview, including loading URLs, HTML content, and reloading the current page.
```typescript
webview.loadUrl(url: string): void
webview.loadHtml(html: string): void
webview.loadUrlWithHeaders(url: string, headers: HeaderData[]): void
webview.reload(): void
webview.url(): string | null // currently displayed URL
```
--------------------------------
### Window Icon and Progress Bar
Source: https://github.com/webviewjs/webview/blob/main/docs/api/browser-window.md
Methods to set the window's icon using RGBA data and to display a progress bar with customizable states and progress values.
```typescript
win.setWindowIcon(rgba: Buffer, width: number, height: number): void
win.setProgressBar(progress: JsProgressBar): void
```
```typescript
interface JsProgressBar {
state?: ProgressBarState; // 'None' | 'Normal' | 'Indeterminate' | 'Paused' | 'Error'
progress?: number; // 0-100
}
```
--------------------------------
### Custom Protocols
Source: https://github.com/webviewjs/webview/blob/main/docs/api/webview.md
Information on registering custom protocols with the BrowserWindow for use in webviews.
```APIDOC
## Custom Protocols
Custom protocols can be registered on the `BrowserWindow` using `win.registerProtocol(scheme, handler)` before `createWebview()` is called.
### `win.registerProtocol(scheme, handler)`
Registers a custom protocol handler.
- **scheme** (string) - The protocol scheme (e.g., 'app').
- **handler** (function) - An async function that takes a request object and returns a response object with `statusCode`, `body`, and `mimeType`.
```
--------------------------------
### Setting a Per-Window Menu
Source: https://github.com/webviewjs/webview/blob/main/docs/api/menu.md
Sets a menu bar for a specific window. This menu will override the global menu for that window only.
```APIDOC
## Setting a Per-Window Menu
### Description
Sets a menu bar for a specific window. This menu will override the global menu for that window only.
### Method
`win.setMenu(options)`
### Parameters
#### Request Body
- **options** (object) - Required - An object conforming to `MenuOptions` that defines the menu structure.
### Request Example
```js
win.setMenu({
items: [/* ... */],
});
```
```
--------------------------------
### Create Incognito Webview
Source: https://github.com/webviewjs/webview/blob/main/docs/guides/cookies-and-storage.md
Initialize a webview in incognito mode by passing `incognito: true`. This ensures that all session data (cookies, cache, local storage) is discarded upon closing the webview.
```javascript
const webview = win.createWebview({
url: 'https://example.com',
incognito: true,
});
```
--------------------------------
### Window State Management
Source: https://github.com/webviewjs/webview/blob/main/docs/api/browser-window.md
Methods to control the window's title, visibility, and state (minimize, maximize, fullscreen, focus).
```typescript
win.setTitle(title: string): void
win.setVisible(visible: boolean): void
win.show(): void
win.hide(): void
win.minimize(): void
win.maximize(): void
win.unmaximize(): void
win.setFullscreen(type: FullscreenType | null): void
win.focus(): void
win.requestRedraw(): void
```
--------------------------------
### Set Global Menu
Source: https://github.com/webviewjs/webview/blob/main/docs/api/menu.md
Define the application-wide menu bar. This function is additive; calling it again replaces the existing menu. Pass null to remove the menu.
```javascript
app.setMenu({
items: [
{
label: 'File',
submenu: {
items: [
{ label: 'New', id: 'file-new', accelerator: 'CmdOrCtrl+N' },
{ label: 'Open', id: 'file-open', accelerator: 'CmdOrCtrl+O' },
{ role: 'separator' },
{ role: 'quit' },
],
},
},
{
label: 'Edit',
submenu: {
items: [
{ role: 'undo' },
{ role: 'redo' },
{ role: 'separator' },
{ role: 'cut' },
{ role: 'copy' },
{ role: 'paste' },
{ role: 'selectall' },
],
},
},
],
});
```
--------------------------------
### Handle IPC Messages in Webview
Source: https://github.com/webviewjs/webview/blob/main/README.md
Illustrates how to set up IPC communication to receive messages from the webview in Node.js. An optional ipcName can be provided to create an alias for posting messages.
```javascript
const webview = window.createWebview({ ipcName: 'bindings' });
webview.onIpcMessage((message) => console.log(message.body.toString()));
```
--------------------------------
### Open Multiple Browser Windows
Source: https://github.com/webviewjs/webview/blob/main/docs/guides/multiple-windows.md
Creates and opens two distinct browser windows with specified URLs. Both windows share the same event loop.
```javascript
const app = new Application();
function createWindow(url) {
const win = app.createBrowserWindow({ title: url, width: 900, height: 600 });
win.createWebview({ url });
return win;
}
const win1 = createWindow('https://example.com');
const win2 = createWindow('https://nodejs.org');
app.run();
```
--------------------------------
### Basic Page to Node IPC
Source: https://github.com/webviewjs/webview/blob/main/docs/guides/ipc-messaging.md
Demonstrates sending a message from a web page to the Node.js backend using `window.ipc.postMessage()` and receiving it with `webview.onIpcMessage()`.
```javascript
const webview = win.createWebview({ html: '' });
webview.onIpcMessage((message) => {
console.log(message.body.toString('utf8'));
});
webview.evaluateScript('
document.querySelector(\'#ping\").addEventListener(\'click\', () => {
window.ipc.postMessage(\'hello from the page\');
});
');
```
--------------------------------
### Creating a Window with a Custom Menu in WebviewJS
Source: https://github.com/webviewjs/webview/blob/main/README.md
Creates a browser window with a specific menu defined in its options. This is useful for providing context-specific menus for individual windows within the application.
```javascript
const app = new Application();
// Create window with custom menu
const window = app.createBrowserWindow({
title: 'Custom Window',
menu: {
items: [
{
id: 'window-action',
label: 'Window Action',
accelerator: 'Ctrl+W',
},
],
},
});
// Or check if window has a menu
if (window.hasMenu()) {
console.log('This window has a menu');
}
```
--------------------------------
### Expose Node.js Functions to Webview
Source: https://github.com/webviewjs/webview/blob/main/examples/assets/expose/index.html
This JavaScript code sets up event listeners and functions to interact with the exposed Node.js bridge. It checks for the `window.native` object, updates the status with native version and properties, and displays the output from `native.readExample()`. Ensure the Node bridge is ready before calling exposed functions.
```javascript
const status = document.querySelector('#status');
const output = document.querySelector('#output');
async function refresh() {
if (!window.native) {
status.textContent = 'Bridge is not ready yet. Try again.';
return;
}
status.textContent = `native.version=${window.native.version}, native.isCool=${window.native.isCool}`;
output.textContent = (await window.native.readExample()).slice(0, 400);
}
document.querySelector('#read').addEventListener('click', () => {
refresh().catch((error) => {
output.textContent = `${error.name}: ${error.message}`;
});
});
window.bindings.postMessage('Expose example is ready');
```
--------------------------------
### Expose Native Functionality to Page
Source: https://github.com/webviewjs/webview/blob/main/docs/api/webview.md
Exposes static JSON values and Node.js functions to the webview's page under a specified global namespace. Arguments and return values must be JSON-serializable.
```javascript
webview.expose('native', {
isCool: true,
readFile: async (path) => readFile(path, 'utf8'),
});
```
```javascript
// In the page
console.log(window.native.isCool);
const text = await window.native.readFile('/tmp/example.txt');
```
--------------------------------
### createChildBrowserWindow(options?)
Source: https://github.com/webviewjs/webview/blob/main/docs/api/application.md
Creates a child or popup window. The webview content will occupy a specific region within the parent window, rather than the entire window.
```APIDOC
## `createChildBrowserWindow(options?)`
Create a child/popup window. The webview fills a precise region inside the parent rather than the whole window.
```ts
app.createChildBrowserWindow(options?: BrowserWindowOptions): BrowserWindow
```
```
--------------------------------
### Webview Navigation
Source: https://github.com/webviewjs/webview/blob/main/docs/api/webview.md
Methods for controlling the navigation of a webview.
```APIDOC
## Navigation Methods
### `loadUrl(url: string): void`
Loads the specified URL in the webview.
### `loadHtml(html: string): void`
Loads the specified HTML content in the webview.
### `loadUrlWithHeaders(url: string, headers: HeaderData[]): void`
Loads the specified URL with custom headers.
### `reload(): void`
Reloads the current page.
### `url(): string | null`
Returns the currently displayed URL or null if none is available.
```
```APIDOC
## HeaderData
Interface for defining custom headers.
### Properties
- **key** (string) - Required - The header key.
- **value** (string) - Optional - The header value.
```
--------------------------------
### Set Per-Window Menu
Source: https://github.com/webviewjs/webview/blob/main/docs/api/menu.md
Configure a menu that applies only to a specific window, overriding the global menu for that window.
```javascript
win.setMenu({
items: [/* … */],
});
```
--------------------------------
### Monitor Info
Source: https://github.com/webviewjs/webview/blob/main/docs/api/browser-window.md
Methods for retrieving information about the current, primary, and available monitors.
```APIDOC
## Monitor info
```ts
win.currentMonitor(): Monitor | null
win.primaryMonitor(): Monitor | null
win.availableMonitors(): Monitor[]
```
```ts
interface Monitor {
name?: string;
scaleFactor: number;
size: Dimensions;
position: Position;
videoModes: VideoMode[];
}
```
```
--------------------------------
### Expose API to Webview
Source: https://github.com/webviewjs/webview/blob/main/docs/api/webview.md
Method for exposing static values and Node.js functions to the webview's global scope.
```APIDOC
## `expose(name, target)`
Exposes JSON-serializable static values and Node.js functions under a specified global name in the webview's JavaScript context. Page functions exposed this way will always return Promises.
### Arguments
- **name** (string) - The name of the global object to expose (e.g., 'native').
- **target** (object) - An object containing the values and functions to expose.
### Limitations
- Only enumerable own data properties are exposed; getters and setters are ignored.
- Arguments, static values, and function results must be JSON-serializable. Cyclic structures, `BigInt`, functions as values, and `undefined` results will cause a `SerializationError`.
- The namespace can only be exposed once per webview.
```
--------------------------------
### Focus Management
Source: https://github.com/webviewjs/webview/blob/main/docs/api/webview.md
Methods for managing keyboard focus for the webview and its parent.
```APIDOC
## Focus Methods
### `focus(): void`
Gives keyboard focus to the webview.
### `focusParent(): void`
Returns keyboard focus to the parent window.
```
--------------------------------
### Expose Asynchronous Functions for Page-to-Node Calls
Source: https://github.com/webviewjs/webview/blob/main/docs/getting-started/quick-start.md
Demonstrates how to expose asynchronous functions from the Node.js backend to the webview using `webview.expose()`. This allows the web page to call Node.js functions and receive their results asynchronously.
```javascript
webview.expose('native', {
getGreeting: async (name) => `Hello, ${name}`,
});
```
--------------------------------
### Script Execution
Source: https://github.com/webviewjs/webview/blob/main/docs/api/webview.md
Methods for executing JavaScript within the webview.
```APIDOC
## Script Execution Methods
### `evaluateScript(script: string): void`
Executes the given JavaScript string in the webview's context.
### `evaluateScriptWithCallback(script: string, callback: (result: string) => void): void`
Executes the given JavaScript string and calls the callback with the result.
```
--------------------------------
### Automatic Cleanup with Symbol.dispose
Source: https://github.com/webviewjs/webview/blob/main/docs/getting-started/quick-start.md
Illustrates the use of `Symbol.dispose` for automatic cleanup of resources like the `Application` instance. When used within a `using` block, the `app.exit()` method is automatically called when the block is exited.
```javascript
{
using app = new Application();
// …
} // app.exit() is called automatically
```
--------------------------------
### Handling Menu Events in WebviewJS
Source: https://github.com/webviewjs/webview/blob/main/README.md
Listens for custom menu click events and logs the clicked item's ID and originating window. This snippet demonstrates how to react to user interactions with custom menu items, such as triggering actions or exiting the application.
```javascript
import { Application, WebviewApplicationEvent } from '@webviewjs/webview';
const app = new Application();
// Handle menu events
app.bind((event) => {
if (event.event === WebviewApplicationEvent.CustomMenuClick) {
const menuEvent = event.customMenuClickEvent;
console.log(`Menu item clicked: ${menuEvent.id}`);
console.log(`From window: ${menuEvent.windowId}`);
// Handle specific menu items
switch (menuEvent.id) {
case 'new':
console.log('Creating new document...');
break;
case 'open':
console.log('Opening file...');
break;
case 'quit':
app.exit();
break;
}
}
});
// Set up menu...
app.setMenu({
/* ... */
});
```
--------------------------------
### IPC (Inter-Process Communication)
Source: https://github.com/webviewjs/webview/blob/main/docs/api/webview.md
Methods for enabling communication between the webview and the Node.js process.
```APIDOC
## IPC Methods
### `onIpcMessage(handler)`
Registers a handler function to receive messages posted from the webview using `window.ipc.postMessage()`.
**Note:** The `ipcName` option during webview creation can be used to set an alias for `window.ipc`.
```