Files
upstream-tauri/packages/api/src/webview.ts
upstream-mirror feda81bf2f
Some checks failed
Audit / audit-js (push) Failing after 0s
bench / bench (map[os:ubuntu-latest runner:xvfb-run --auto-servernum target:x86_64-unknown-linux-gnu], nightly) (push) Failing after 0s
covector version or publish / run-integration-tests (ubuntu-latest) (push) Failing after 0s
Audit / audit-rust (push) Failing after 0s
test `@tauri-apps/cli` / test (ubuntu-latest) (push) Failing after 0s
test `tauri-cli` / test (map[os:ubuntu-latest target:x86_64-unknown-linux-gnu]) (push) Failing after 0s
test core / test (map[args:--all-features key:all], map[cargo:cargo command:test os:ubuntu-latest target:x86_64-unknown-linux-gnu toolchain:1.90]) (push) Failing after 0s
test core / test (map[args:--no-default-features key:no-default], map[cargo:cargo command:test os:ubuntu-latest target:x86_64-unknown-linux-gnu toolchain:1.90]) (push) Failing after 0s
test core / test (map[args:--no-default-features key:no-default], map[cargo:cross command:build os:ubuntu-latest target:aarch64-linux-android toolchain:1.90]) (push) Failing after 0s
deploy schema worker / deploy (push) Failing after 0s
lint rust / clippy (map[cargo:cargo include: os:ubuntu-latest target:x86_64-unknown-linux-gnu]) (push) Failing after 0s
lint rust / clippy (map[cargo:cross include:--package api os:ubuntu-latest target:aarch64-linux-android]) (push) Failing after 0s
supply chain health status / check rust dependencies with cargo vet (push) Failing after 0s
test `@tauri-apps/api` e2e (mobile) / android (push) Failing after 0s
test `@tauri-apps/api` e2e / test (map[name:Linux os:ubuntu-latest]) (push) Failing after 0s
test core / test (map[args:--all-features key:all], map[cargo:cross command:build os:ubuntu-latest target:aarch64-linux-android toolchain:1.90]) (push) Failing after 0s
Udeps / changes (push) Failing after 0s
Udeps / setup (push) Has been skipped
Udeps / udeps (push) Has been skipped
bench / bench (map[os:macos-latest runner: target:aarch64-apple-darwin], nightly) (push) Has been cancelled
bench / bench (map[os:windows-latest runner: target:x86_64-pc-windows-msvc], nightly) (push) Has been cancelled
covector version or publish / run-integration-tests (macos-latest) (push) Has been cancelled
covector version or publish / run-integration-tests (windows-latest) (push) Has been cancelled
covector version or publish / version-or-publish (push) Has been cancelled
test `@tauri-apps/cli` / test (macos-latest) (push) Has been cancelled
test `tauri-cli` / test (map[args:--no-default-features --features native-tls-vendored os:windows-latest restore-only:true target:aarch64-pc-windows-msvc]) (push) Has been cancelled
test `tauri-cli` / test (map[os:macos-latest target:x86_64-apple-darwin]) (push) Has been cancelled
test `tauri-cli` / test (map[os:windows-latest target:x86_64-pc-windows-msvc]) (push) Has been cancelled
test core / test (map[args:--all-features key:all], map[cargo:cargo command:build os:macos-latest target:aarch64-apple-ios toolchain:1.90]) (push) Has been cancelled
test core / test (map[args:--all-features key:all], map[cargo:cargo command:test os:macos-14 target:aarch64-apple-darwin toolchain:1.90]) (push) Has been cancelled
lint rust / clippy (map[cargo:cargo include: os:macos-latest target:aarch64-apple-darwin]) (push) Has been cancelled
lint rust / clippy (map[cargo:cargo include: os:windows-latest target:x86_64-pc-windows-msvc]) (push) Has been cancelled
lint rust / clippy (map[cargo:cargo include:--package api os:macos-latest target:aarch64-apple-ios]) (push) Has been cancelled
test `@tauri-apps/api` e2e (mobile) / ios (push) Has been cancelled
test `@tauri-apps/api` e2e / test (map[name:Windows os:windows-latest]) (push) Has been cancelled
test `@tauri-apps/api` e2e / test (map[name:macOS os:macos-latest]) (push) Has been cancelled
test `@tauri-apps/cli` / test (windows-latest) (push) Has been cancelled
test core / test (map[args:--all-features key:all], map[cargo:cargo command:test os:windows-latest target:x86_64-pc-windows-msvc toolchain:1.90]) (push) Has been cancelled
test core / test (map[args:--no-default-features key:no-default], map[cargo:cargo command:build os:macos-latest target:aarch64-apple-ios toolchain:1.90]) (push) Has been cancelled
test core / test (map[args:--no-default-features key:no-default], map[cargo:cargo command:test os:macos-14 target:aarch64-apple-darwin toolchain:1.90]) (push) Has been cancelled
test core / test (map[args:--no-default-features key:no-default], map[cargo:cargo command:test os:windows-latest target:x86_64-pc-windows-msvc toolchain:1.90]) (push) Has been cancelled
snapshot of https://github.com/tauri-apps/tauri.git (dev, 2026-09-23; blobs > 131072B omitted)
2026-09-23 17:00:42 +05:00

1052 lines
34 KiB
TypeScript

// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
/**
* Provides APIs to create webviews, communicate with other webviews and manipulate the current webview.
*
* #### Webview events
*
* Events can be listened to using {@link Webview.listen}:
* ```typescript
* import { getCurrentWebview } from "@tauri-apps/api/webview";
* getCurrentWebview().listen("my-webview-event", ({ event, payload }) => { });
* ```
*
* #### The `unstable` Cargo feature
*
* Creating *child webviews* — several webviews inside one window, via
* {@link Webview | `new Webview(...)`} — is an unstable API. It requires the
* `unstable` feature of the `tauri` crate:
*
* ```toml
* [dependencies]
* tauri = { version = "2", features = ["unstable"] }
* ```
*
* Without it the `plugin:webview|create_webview` command returns an
* "unstable feature not supported" error. Everything else in this module —
* {@link getCurrentWebview}, {@link getAllWebviews} and the methods of an existing
* webview — works without the feature, and so does
* {@link WebviewWindow | `new WebviewWindow(...)`}, which creates a window with a
* single webview.
*
* This package is also accessible with `window.__TAURI__.webview` when [`app.withGlobalTauri`](https://v2.tauri.app/reference/config/#withglobaltauri) in `tauri.conf.json` is set to `true`.
*
* @remarks `core:webview:default` only enables the getters
* (`allow-get-all-webviews`, `allow-webview-position`, `allow-webview-size` and
* `allow-internal-toggle-devtools`). Every other method documents the permission
* it needs, which you must add to a capability yourself.
*
* @module
*/
import { PhysicalPosition, PhysicalSize } from './dpi'
import type { LogicalPosition, LogicalSize } from './dpi'
import { Position, Size } from './dpi'
import type { EventName, EventCallback, UnlistenFn } from './event'
import {
TauriEvent,
// imported for documentation purposes
type EventTarget,
emit,
emitTo,
listen,
once
} from './event'
import { invoke } from './core'
import {
BackgroundThrottlingPolicy,
ScrollBarStyle,
Color,
Window,
getCurrentWindow
} from './window'
import { WebviewWindow } from './webviewWindow'
/**
* The payload of a drag and drop event, see {@link Webview.onDragDropEvent}.
*
* - `enter`: the user dragged files over the webview; `paths` holds the dragged files.
* - `over`: the cursor moved while dragging; only `position` changes.
* - `drop`: the files were dropped; `paths` holds the dropped files.
* - `leave`: the drag left the webview or was cancelled.
*
* Positions are in physical pixels, relative to the webview's top-left corner.
*/
type DragDropEvent =
| { type: 'enter'; paths: string[]; position: PhysicalPosition }
| { type: 'over'; position: PhysicalPosition }
| { type: 'drop'; paths: string[]; position: PhysicalPosition }
| { type: 'leave' }
/**
* Get an instance of `Webview` for the current webview.
*
* @since 2.0.0
*/
function getCurrentWebview(): Webview {
return new Webview(
getCurrentWindow(),
window.__TAURI_INTERNALS__.metadata.currentWebview.label,
{
// @ts-expect-error `skip` is not defined in the public API but it is handled by the constructor
skip: true
}
)
}
/**
* Gets a list of instances of `Webview` for all available webviews.
*
* @remarks Uses the `core:webview:allow-get-all-webviews` permission, which is part
* of `core:webview:default`.
*
* @since 2.0.0
*/
async function getAllWebviews(): Promise<Webview[]> {
return invoke<Array<{ windowLabel: string; label: string }>>(
'plugin:webview|get_all_webviews'
).then((webviews) =>
webviews.map(
(w) =>
new Webview(
new Window(w.windowLabel, {
// @ts-expect-error `skip` is not defined in the public API but it is handled by the constructor
skip: true
}),
w.label,
{
// @ts-expect-error `skip` is not defined in the public API but it is handled by the constructor
skip: true
}
)
)
)
}
/** @ignore */
// events that are emitted right here instead of by the created webview
const localTauriEvents = ['tauri://created', 'tauri://error']
/** @ignore */
export type WebviewLabel = string
/**
* Create new webview or get a handle to an existing one.
*
* Webviews are identified by a *label* a unique identifier that can be used to reference it later.
* It may only contain alphanumeric characters `a-zA-Z` plus the following special characters `-`, `/`, `:` and `_`.
*
* #### Requires the `unstable` Cargo feature
*
* Creating a webview with `new Webview(...)` adds a *child webview* to an existing
* window, which is an unstable API gated behind the `unstable` feature of the
* `tauri` crate:
*
* ```toml
* [dependencies]
* tauri = { version = "2", features = ["unstable"] }
* ```
*
* Without it the call rejects with an "unstable feature not supported" error.
* Getting a handle to an existing webview (`Webview.getByLabel`,
* {@link getCurrentWebview}, {@link getAllWebviews}) and every method on this class
* work without the feature. To create a window that hosts a single webview, use
* {@link WebviewWindow} instead, which is stable.
*
* @example
* ```typescript
* import { Window } from "@tauri-apps/api/window"
* import { Webview } from "@tauri-apps/api/webview"
*
* const appWindow = new Window('uniqueLabel');
*
* appWindow.once('tauri://created', async function () {
* // `new Webview` Should be called after the window is successfully created,
* // or webview may not be attached to the window since window is not created yet.
*
* // loading embedded asset:
* const webview = new Webview(appWindow, 'theUniqueLabel', {
* url: 'path/to/page.html',
*
* // create a webview with specific logical position and size
* x: 0,
* y: 0,
* width: 800,
* height: 600,
* });
* // alternatively, load a remote URL:
* const webview = new Webview(appWindow, 'theUniqueLabel', {
* url: 'https://github.com/tauri-apps/tauri',
*
* // create a webview with specific logical position and size
* x: 0,
* y: 0,
* width: 800,
* height: 600,
* });
*
* webview.once('tauri://created', function () {
* // webview successfully created
* });
* webview.once('tauri://error', function (e) {
* // an error happened creating the webview
* });
*
*
* // emit an event to the backend
* await webview.emit("some-event", "data");
* // listen to an event from the backend
* const unlisten = await webview.listen("event-name", e => { });
* unlisten();
* });
* ```
*
* @since 2.0.0
*/
class Webview {
/** The webview label. It is a unique identifier for the webview, can be used to reference it later. */
label: WebviewLabel
/** The window hosting this webview. */
window: Window
/** Local event listeners. */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
listeners: Record<string, Array<EventCallback<any>>>
/**
* Creates a new Webview.
* @example
* ```typescript
* import { Window } from '@tauri-apps/api/window'
* import { Webview } from '@tauri-apps/api/webview'
* const appWindow = new Window('my-label')
*
* appWindow.once('tauri://created', async function() {
* const webview = new Webview(appWindow, 'my-label', {
* url: 'https://github.com/tauri-apps/tauri',
*
* // create a webview with specific logical position and size
* x: 0,
* y: 0,
* width: 800,
* height: 600,
* });
*
* webview.once('tauri://created', function () {
* // webview successfully created
* });
* webview.once('tauri://error', function (e) {
* // an error happened creating the webview
* });
* });
* ```
*
* @param window the window to add this webview to.
* @param label The unique webview label. Must be alphanumeric: `a-zA-Z-/:_`.
* @param options The webview configuration, see {@link WebviewOptions}.
* @returns The {@link Webview} instance to communicate with the webview.
*
* @remarks Requires the `unstable` Cargo feature on the `tauri` crate
* (`tauri = { version = "2", features = ["unstable"] }`), otherwise the call
* rejects with an "unstable feature not supported" error. It also requires the
* `core:webview:allow-create-webview` permission, which is not included in
* `core:webview:default`.
*/
constructor(window: Window, label: WebviewLabel, options: WebviewOptions) {
this.window = window
this.label = label
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
this.listeners = Object.create(null)
// @ts-expect-error `skip` is not a public API so it is not defined in WebviewOptions
if (!options?.skip) {
invoke('plugin:webview|create_webview', {
windowLabel: window.label,
options: {
...options,
label
}
})
.then(async () => this.emit('tauri://created'))
.catch(async (e: string) => this.emit('tauri://error', e))
}
}
/**
* Gets the Webview for the webview associated with the given label.
* @example
* ```typescript
* import { Webview } from '@tauri-apps/api/webview';
* const mainWebview = Webview.getByLabel('main');
* ```
*
* @param label The webview label.
* @returns The Webview instance to communicate with the webview or null if the webview doesn't exist.
*/
static async getByLabel(label: string): Promise<Webview | null> {
return (await getAllWebviews()).find((w) => w.label === label) ?? null
}
/**
* Get an instance of `Webview` for the current webview.
*/
static getCurrent(): Webview {
return getCurrentWebview()
}
/**
* Gets a list of instances of `Webview` for all available webviews.
*/
static async getAll(): Promise<Webview[]> {
return getAllWebviews()
}
/**
* Listen to an emitted event on this webview.
*
* @example
* ```typescript
* import { getCurrentWebview } from '@tauri-apps/api/webview';
* const unlisten = await getCurrentWebview().listen<string>('state-changed', (event) => {
* console.log(`Got error: ${payload}`);
* });
*
* // call unlisten when your handler goes out of scope e.g. the component is unmounted
* unlisten();
* ```
*
* @param event Event name. Must include only alphanumeric characters, `-`, `/`, `:` and `_`.
* @param handler Event handler.
* @returns A promise resolving to a function to unlisten to the event.
*
* @remarks The listener is removed automatically when this webview is destroyed,
* so you do not need to unlisten just because the webview is closing. Do call the
* returned function when the listener's own scope ends, e.g. on page navigation
* or when a component unmounts.
*/
async listen<T>(
event: EventName,
handler: EventCallback<T>
): Promise<UnlistenFn> {
if (this._handleTauriEvent(event, handler)) {
return () => {
// eslint-disable-next-line security/detect-object-injection
const listeners = this.listeners[event]
listeners.splice(listeners.indexOf(handler), 1)
}
}
return listen(event, handler, {
target: { kind: 'Webview', label: this.label }
})
}
/**
* Listen to an emitted event on this webview only once.
*
* @example
* ```typescript
* import { getCurrentWebview } from '@tauri-apps/api/webview';
* const unlisten = await getCurrentWebview().once<null>('initialized', (event) => {
* console.log(`Webview initialized!`);
* });
*
* // call unlisten when your handler goes out of scope e.g. the component is unmounted
* unlisten();
* ```
*
* @param event Event name. Must include only alphanumeric characters, `-`, `/`, `:` and `_`.
* @param handler Event handler.
* @returns A promise resolving to a function to unlisten to the event.
*
* @remarks The listener removes itself after the first event and is also removed
* automatically when this webview is destroyed. Do call the returned function if
* the listener's own scope ends before the event arrives.
*/
async once<T>(
event: EventName,
handler: EventCallback<T>
): Promise<UnlistenFn> {
if (this._handleTauriEvent(event, handler)) {
return () => {
// eslint-disable-next-line security/detect-object-injection
const listeners = this.listeners[event]
listeners.splice(listeners.indexOf(handler), 1)
}
}
return once(event, handler, {
target: { kind: 'Webview', label: this.label }
})
}
/**
* Emits an event to all {@link EventTarget|targets}.
*
* @example
* ```typescript
* import { getCurrentWebview } from '@tauri-apps/api/webview';
* await getCurrentWebview().emit('webview-loaded', { loggedIn: true, token: 'authToken' });
* ```
*
* @param event Event name. Must include only alphanumeric characters, `-`, `/`, `:` and `_`.
* @param payload Event payload.
*/
async emit<T>(event: string, payload?: T): Promise<void> {
if (localTauriEvents.includes(event)) {
// eslint-disable-next-line
for (const handler of this.listeners[event] || []) {
handler({
event,
id: -1,
payload
})
}
return
}
return emit<T>(event, payload)
}
/**
* Emits an event to all {@link EventTarget|targets} matching the given target.
*
* @example
* ```typescript
* import { getCurrentWebview } from '@tauri-apps/api/webview';
* await getCurrentWebview().emitTo('main', 'webview-loaded', { loggedIn: true, token: 'authToken' });
* ```
*
* @param target Label of the target Window/Webview/WebviewWindow or raw {@link EventTarget} object.
* @param event Event name. Must include only alphanumeric characters, `-`, `/`, `:` and `_`.
* @param payload Event payload.
*/
async emitTo<T>(
target: string | EventTarget,
event: string,
payload?: T
): Promise<void> {
if (localTauriEvents.includes(event)) {
// eslint-disable-next-line
for (const handler of this.listeners[event] || []) {
handler({
event,
id: -1,
payload
})
}
return
}
return emitTo<T>(target, event, payload)
}
/** @ignore */
_handleTauriEvent<T>(event: string, handler: EventCallback<T>): boolean {
if (localTauriEvents.includes(event)) {
if (!(event in this.listeners)) {
// eslint-disable-next-line security/detect-object-injection
this.listeners[event] = [handler]
} else {
// eslint-disable-next-line security/detect-object-injection
this.listeners[event].push(handler)
}
return true
}
return false
}
// Getters
/**
* The position of the top-left hand corner of the webview's client area relative to the top-left hand corner of the desktop.
* @example
* ```typescript
* import { getCurrentWebview } from '@tauri-apps/api/webview';
* const position = await getCurrentWebview().position();
* ```
*
* @returns The webview's position, in physical pixels.
*
* @remarks Uses the `core:webview:allow-webview-position` permission, which is
* part of `core:webview:default`.
*/
async position(): Promise<PhysicalPosition> {
return invoke<{ x: number; y: number }>('plugin:webview|webview_position', {
label: this.label
}).then((p) => new PhysicalPosition(p))
}
/**
* The physical size of the webview's client area.
* The client area is the content of the webview, excluding the title bar and borders.
* @example
* ```typescript
* import { getCurrentWebview } from '@tauri-apps/api/webview';
* const size = await getCurrentWebview().size();
* ```
*
* @returns The webview's size, in physical pixels.
*
* @remarks Uses the `core:webview:allow-webview-size` permission, which is part
* of `core:webview:default`.
*/
async size(): Promise<PhysicalSize> {
return invoke<{ width: number; height: number }>(
'plugin:webview|webview_size',
{
label: this.label
}
).then((s) => new PhysicalSize(s))
}
// Setters
/**
* Closes the webview.
* @example
* ```typescript
* import { getCurrentWebview } from '@tauri-apps/api/webview';
* await getCurrentWebview().close();
* ```
*
* @returns A promise indicating the success or failure of the operation.
*
* @remarks Requires the `core:webview:allow-webview-close` permission (not
* included in `core:webview:default`).
*/
async close(): Promise<void> {
return invoke('plugin:webview|webview_close', {
label: this.label
})
}
/**
* Resizes the webview.
* @example
* ```typescript
* import { getCurrentWebview } from '@tauri-apps/api/webview';
* import { LogicalSize } from '@tauri-apps/api/dpi';
* await getCurrentWebview().setSize(new LogicalSize(600, 500));
* ```
*
* @param size The logical or physical size.
* @returns A promise indicating the success or failure of the operation.
*
* @remarks Requires the `core:webview:allow-set-webview-size` permission (not
* included in `core:webview:default`).
*/
async setSize(size: LogicalSize | PhysicalSize | Size): Promise<void> {
return invoke('plugin:webview|set_webview_size', {
label: this.label,
value: size instanceof Size ? size : new Size(size)
})
}
/**
* Sets the webview position.
* @example
* ```typescript
* import { getCurrentWebview } from '@tauri-apps/api/webview';
* import { LogicalPosition } from '@tauri-apps/api/dpi';
* await getCurrentWebview().setPosition(new LogicalPosition(600, 500));
* ```
*
* @param position The new position, in logical or physical pixels, relative to
* the top-left corner of the hosting window.
* @returns A promise indicating the success or failure of the operation.
*
* @remarks Requires the `core:webview:allow-set-webview-position` permission (not
* included in `core:webview:default`).
*/
async setPosition(
position: LogicalPosition | PhysicalPosition | Position
): Promise<void> {
return invoke('plugin:webview|set_webview_position', {
label: this.label,
value: position instanceof Position ? position : new Position(position)
})
}
/**
* Bring the webview to front and focus.
* @example
* ```typescript
* import { getCurrentWebview } from '@tauri-apps/api/webview';
* await getCurrentWebview().setFocus();
* ```
*
* @returns A promise indicating the success or failure of the operation.
*
* @remarks Requires the `core:webview:allow-set-webview-focus` permission (not
* included in `core:webview:default`).
*/
async setFocus(): Promise<void> {
return invoke('plugin:webview|set_webview_focus', {
label: this.label
})
}
/**
* Sets whether the webview should automatically grow and shrink its size and position when the parent window resizes.
* @example
* ```typescript
* import { getCurrentWebview } from '@tauri-apps/api/webview';
* await getCurrentWebview().setAutoResize(true);
* ```
*
* @returns A promise indicating the success or failure of the operation.
*
* @remarks Requires the `core:webview:allow-set-webview-auto-resize` permission
* (not included in `core:webview:default`).
*/
async setAutoResize(autoResize: boolean): Promise<void> {
return invoke('plugin:webview|set_webview_auto_resize', {
label: this.label,
value: autoResize
})
}
/**
* Hide the webview.
* @example
* ```typescript
* import { getCurrentWebview } from '@tauri-apps/api/webview';
* await getCurrentWebview().hide();
* ```
*
* @returns A promise indicating the success or failure of the operation.
*
* @remarks Requires the `core:webview:allow-webview-hide` permission (not
* included in `core:webview:default`).
*/
async hide(): Promise<void> {
return invoke('plugin:webview|webview_hide', {
label: this.label
})
}
/**
* Show the webview.
* @example
* ```typescript
* import { getCurrentWebview } from '@tauri-apps/api/webview';
* await getCurrentWebview().show();
* ```
*
* @returns A promise indicating the success or failure of the operation.
*
* @remarks Requires the `core:webview:allow-webview-show` permission (not
* included in `core:webview:default`).
*/
async show(): Promise<void> {
return invoke('plugin:webview|webview_show', {
label: this.label
})
}
/**
* Set webview zoom level.
* @example
* ```typescript
* import { getCurrentWebview } from '@tauri-apps/api/webview';
* await getCurrentWebview().setZoom(1.5);
* ```
*
* @param scaleFactor The zoom level, where `1` is 100%.
* @returns A promise indicating the success or failure of the operation.
*
* @remarks Requires the `core:webview:allow-set-webview-zoom` permission (not
* included in `core:webview:default`).
*/
async setZoom(scaleFactor: number): Promise<void> {
return invoke('plugin:webview|set_webview_zoom', {
label: this.label,
value: scaleFactor
})
}
/**
* Moves this webview to the window with the given label.
* @example
* ```typescript
* import { getCurrentWebview } from '@tauri-apps/api/webview';
* await getCurrentWebview().reparent('other-window');
* ```
*
* @param window The target window, or its label.
* @returns A promise indicating the success or failure of the operation.
*
* @remarks Requires the `core:webview:allow-reparent` permission (not included in
* `core:webview:default`).
*/
async reparent(window: Window | WebviewWindow | string): Promise<void> {
return invoke('plugin:webview|reparent', {
label: this.label,
window: typeof window === 'string' ? window : window.label
})
}
/**
* Clears all browsing data for this webview: cookies, localStorage, IndexedDB,
* caches and any other data the webview stores for the loaded origins.
* @example
* ```typescript
* import { getCurrentWebview } from '@tauri-apps/api/webview';
* await getCurrentWebview().clearAllBrowsingData();
* ```
*
* @returns A promise indicating the success or failure of the operation.
*
* @remarks Requires the `core:webview:allow-clear-all-browsing-data` permission
* (not included in `core:webview:default`).
*/
async clearAllBrowsingData(): Promise<void> {
return invoke('plugin:webview|clear_all_browsing_data')
}
/**
* Specify the webview background color.
*
* #### Platform-specific:
*
* - **macOS / iOS**: Not implemented.
* - **Windows**:
* - On Windows 7, transparency is not supported and the alpha value will be ignored.
* - On Windows higher than 7: translucent colors are not supported so any alpha value other than `0` will be replaced by `255`
*
* @example
* ```typescript
* import { getCurrentWebview } from '@tauri-apps/api/webview';
* await getCurrentWebview().setBackgroundColor('#2f2f2f');
* // or with an RGBA tuple, or `null` to restore the default background
* await getCurrentWebview().setBackgroundColor([47, 47, 47, 255]);
* ```
*
* @param color The new background color, or `null` to reset it.
* @returns A promise indicating the success or failure of the operation.
*
* @remarks Requires the `core:webview:allow-set-webview-background-color`
* permission (not included in `core:webview:default`).
*
* @since 2.1.0
*/
async setBackgroundColor(color: Color | null): Promise<void> {
return invoke('plugin:webview|set_webview_background_color', {
label: this.label,
value: color
})
}
// Listeners
/**
* Listen to a file drop event.
* The listener is triggered when the user hovers the selected files on the webview,
* drops the files or cancels the operation.
*
* @example
* ```typescript
* import { getCurrentWebview } from "@tauri-apps/api/webview";
* const unlisten = await getCurrentWebview().onDragDropEvent((event) => {
* if (event.payload.type === 'over') {
* console.log('User hovering', event.payload.position);
* } else if (event.payload.type === 'drop') {
* console.log('User dropped', event.payload.paths);
* } else {
* console.log('File drop cancelled');
* }
* });
*
* // call unlisten when your handler goes out of scope e.g. the component is unmounted
* unlisten();
* ```
*
* When the debugger panel is open, the drop position of this event may be inaccurate due to a known limitation.
* To retrieve the correct drop position, please detach the debugger.
*
* @returns A promise resolving to a function to unlisten to the event.
*
* @remarks The listeners are removed automatically when this webview is
* destroyed. Do call the returned function when the listener's own scope ends,
* e.g. on page navigation or when a component unmounts.
*/
async onDragDropEvent(
handler: EventCallback<DragDropEvent>
): Promise<UnlistenFn> {
type DragPayload = { paths: string[]; position: PhysicalPosition }
const unlistenDragEnter = await this.listen<DragPayload>(
TauriEvent.DRAG_ENTER,
(event) => {
handler({
...event,
payload: {
type: 'enter',
paths: event.payload.paths,
position: new PhysicalPosition(event.payload.position)
}
})
}
)
const unlistenDragOver = await this.listen<DragPayload>(
TauriEvent.DRAG_OVER,
(event) => {
handler({
...event,
payload: {
type: 'over',
position: new PhysicalPosition(event.payload.position)
}
})
}
)
const unlistenDragDrop = await this.listen<DragPayload>(
TauriEvent.DRAG_DROP,
(event) => {
handler({
...event,
payload: {
type: 'drop',
paths: event.payload.paths,
position: new PhysicalPosition(event.payload.position)
}
})
}
)
const unlistenDragLeave = await this.listen<null>(
TauriEvent.DRAG_LEAVE,
(event) => {
handler({ ...event, payload: { type: 'leave' } })
}
)
return () => {
unlistenDragEnter()
unlistenDragDrop()
unlistenDragOver()
unlistenDragLeave()
}
}
}
/**
* Configuration for the webview to create.
*
* @since 2.0.0
*/
interface WebviewOptions {
/**
* Remote URL or local file path to open.
*
* - URL such as `https://github.com/tauri-apps` is opened directly on a Tauri webview.
* - data: URL such as `data:text/html,<html>...` is only supported with the `webview-data-url` Cargo feature for the `tauri` dependency.
* - local file path or route such as `/path/to/page.html` or `/users` is appended to the application URL (the devServer URL on development, or `tauri://localhost/` and `https://tauri.localhost/` on production).
*/
url?: string
/** The initial horizontal position in logical pixels, relative to the window's top-left corner. */
x: number
/** The initial vertical position in logical pixels, relative to the window's top-left corner. */
y: number
/** The initial width in logical pixels. */
width: number
/** The initial height in logical pixels. */
height: number
/**
* Whether the webview is transparent or not.
* Note that on `macOS` this requires the `macos-private-api` feature flag, enabled under `tauri.conf.json > app > macOSPrivateApi`.
* WARNING: Using private APIs on `macOS` prevents your application from being accepted to the `App Store`.
*/
transparent?: boolean
/**
* Whether the webview should have focus or not
*
* @since 2.1.0
*/
focus?: boolean
/**
* Whether the drag and drop is enabled or not on the webview. By default it is enabled.
*
* Disabling it is required to use HTML5 drag and drop on the frontend on Windows.
*/
dragDropEnabled?: boolean
/**
* Whether clicking an inactive webview also clicks through to the webview on macOS.
*/
acceptFirstMouse?: boolean
/**
* The user agent for the webview.
*/
userAgent?: string
/**
* Whether or not the webview should be launched in incognito mode.
*
* #### Platform-specific
*
* - **Android:** Unsupported.
*/
incognito?: boolean
/**
* The proxy URL for the WebView for all network requests.
*
* Must be either a `http://` or a `socks5://` URL.
*
* #### Platform-specific
*
* - **macOS**: Requires the `macos-proxy` feature flag and only compiles for macOS 14+.
* */
proxyUrl?: string
/**
* Whether page zooming by hotkeys is enabled
*
* #### Platform-specific:
*
* - **Windows**: Controls WebView2's [`IsZoomControlEnabled`](https://learn.microsoft.com/en-us/microsoft-edge/webview2/reference/winrt/microsoft_web_webview2_core/corewebview2settings?view=webview2-winrt-1.0.2420.47#iszoomcontrolenabled) setting.
* - **MacOS / Linux**: Injects a polyfill that zooms in and out with `ctrl/command` + `-/=`,
* 20% in each step, ranging from 20% to 1000%. Requires `webview:allow-set-webview-zoom` permission
*
* - **Android / iOS**: Unsupported.
*/
zoomHotkeysEnabled?: boolean
/**
* Sets whether the custom protocols should use `https://<scheme>.localhost` instead of the default `http://<scheme>.localhost` on Windows and Android. Defaults to `false`.
*
* #### Note
*
* Using a `https` scheme will NOT allow mixed content when trying to fetch `http` endpoints and therefore will not match the behavior of the `<scheme>://localhost` protocols used on macOS and Linux.
*
* #### Warning
*
* Changing this value between releases will change the IndexedDB, cookies and localstorage location and your app will not be able to access them.
*
* @since 2.1.0
*/
useHttpsScheme?: boolean
/**
* Whether web inspector, which is usually called browser devtools, is enabled or not. Enabled by default.
*
* This API works in **debug** builds, but requires `devtools` feature flag to enable it in **release** builds.
*
* #### Platform-specific
*
* - macOS: This will call private functions on **macOS**.
* - Android: Open `chrome://inspect/#devices` in Chrome to get the devtools window. Wry's `WebView` devtools API isn't supported on Android.
* - iOS: Open Safari > Develop > [Your Device Name] > [Your WebView] to get the devtools window.
*
* @since 2.1.0
*/
devtools?: boolean
/**
* Set the window and webview background color.
*
* #### Platform-specific:
*
* - **macOS / iOS**: Not implemented.
* - **Windows**:
* - On Windows 7, alpha channel is ignored.
* - On Windows 8 and newer, if alpha channel is not `0`, it will be ignored.
*
* @since 2.1.0
*/
backgroundColor?: Color
/** Change the default background throttling behaviour.
*
* By default, browsers use a suspend policy that will throttle timers and even unload
* the whole tab (view) to free resources after roughly 5 minutes when a view became
* minimized or hidden. This will pause all tasks until the documents visibility state
* changes back from hidden to visible by bringing the view back to the foreground.
*
* ## Platform-specific
*
* - **Linux / Windows / Android**: Unsupported. Workarounds like a pending WebLock transaction might suffice.
* - **iOS**: Supported since version 17.0+.
* - **macOS**: Supported since version 14.0+.
*
* see https://github.com/tauri-apps/tauri/issues/5250#issuecomment-2569380578
*
* @since 2.3.0
*/
backgroundThrottling?: BackgroundThrottlingPolicy
/**
* Whether we should disable JavaScript code execution on the webview or not.
*/
javascriptDisabled?: boolean
/**
* on macOS and iOS there is a link preview on long pressing links, this is enabled by default.
* see https://docs.rs/objc2-web-kit/latest/objc2_web_kit/struct.WKWebView.html#method.allowsLinkPreview
*/
allowLinkPreview?: boolean
/**
* Allows disabling the input accessory view on iOS.
*
* The accessory view is the view that appears above the keyboard when a text input element is focused.
* It usually displays a view with "Done", "Next" buttons.
*/
disableInputAccessoryView?: boolean
/**
* Set a custom path for the webview's data directory (localStorage, cache, etc.) **relative to [`appDataDir()`]/${label}**.
* For security reasons, paths outside of that location can only be configured on the Rust side.
*
* #### Platform-specific:
*
* - **Windows**: WebViews with different values for settings like `additionalBrowserArgs`, `browserExtensionsEnabled` or `scrollBarStyle` must have different data directories.
* - **macOS / iOS**: Unsupported, use `dataStoreIdentifier` instead.
* - **Android**: Unsupported.
*
* @since 2.9.0
*/
dataDirectory?: string
/**
* Initialize the WebView with a custom data store identifier. This can be seen as a replacement for `dataDirectory` which is unavailable in WKWebView.
* See https://developer.apple.com/documentation/webkit/wkwebsitedatastore/init(foridentifier:)?language=objc
*
* The array must contain 16 u8 numbers.
*
* #### Platform-specific:
*
* - **macOS / iOS**: Available on macOS >= 14 and iOS >= 17
* - **Windows / Linux / Android**: Unsupported.
*
* @since 2.9.0
*/
dataStoreIdentifier?: number[]
/**
* Specifies the native scrollbar style to use with the webview.
* CSS styles that modify the scrollbar are applied on top of the native appearance configured here.
*
* Defaults to `default`, which is the browser default.
*
* ## Platform-specific
*
* - **Windows**:
* - `fluentOverlay` requires WebView2 Runtime version 125.0.2535.41 or higher, and does nothing
* on older versions.
* - This option must be given the same value for all webviews.
* - **Linux / Android / iOS / macOS**: Unsupported. Only supports `Default` and performs no operation.
*/
scrollBarStyle?: ScrollBarStyle
/**
* Controls the WebView's browser-level general autofill behavior.
*
* **This option does not disable password or credit card autofill.**
*
* When set to `false`, the WebView will not automatically populate general form
* fields using previously stored data such as addresses or contact information.
*
* If not specified, this is `true` by default.
*
* ## Platform-specific
*
* - **Windows**: Supported. WebView2's autofill feature (called "Suggestions")
* may not honor `autocomplete="off"` on input elements in some cases.
* - **Linux / Android / iOS / macOS**: Unsupported and performs no operation.
*
* @since 2.11.0
*/
generalAutofillEnabled?: boolean
}
export { Webview, getCurrentWebview, getAllWebviews }
export type { DragDropEvent, WebviewOptions, Color }