Skip to content
Tauri 中文网

webview

Provides APIs to create webviews, communicate with other webviews and manipulate the current webview.

Events can be listened to using Webview.listen:

import { getCurrentWebview } from "@tauri-apps/api/webview";
getCurrentWebview().listen("my-webview-event", ({ event, payload }) => { });

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 _.

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();
});

2.0.0

new Webview(
window,
label,
options): Webview

Creates a new Webview.

ParameterTypeDescription
windowWindowthe window to add this webview to.
labelstringThe unique webview label. Must be alphanumeric: a-zA-Z-/:_.
optionsWebviewOptions-

Webview

The Webview instance to communicate with the webview.

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
});
});

Source: undefined

PropertyTypeDescriptionDefined in
labelstringThe webview label. It is a unique identifier for the webview, can be used to reference it later.Source: undefined
listenersRecord<string, EventCallback<any>[]>Local event listeners.Source: undefined
windowWindowThe window hosting this webview.Source: undefined

clearAllBrowsingData(): Promise<void>

Clears all browsing data for this webview.

Promise<void>

A promise indicating the success or failure of the operation.

import { getCurrentWebview } from '@tauri-apps/api/webview';
await getCurrentWebview().clearAllBrowsingData();

Source: undefined

close(): Promise<void>

Closes the webview.

Promise<void>

A promise indicating the success or failure of the operation.

import { getCurrentWebview } from '@tauri-apps/api/webview';
await getCurrentWebview().close();

Source: undefined

emit<T>(event, payload?): Promise<void>

Emits an event to all targets.

Type Parameter
T
ParameterTypeDescription
eventstringEvent name. Must include only alphanumeric characters, -, /, : and _.
payload?TEvent payload.

Promise<void>

import { getCurrentWebview } from '@tauri-apps/api/webview';
await getCurrentWebview().emit('webview-loaded', { loggedIn: true, token: 'authToken' });

Source: undefined

emitTo<T>(
target,
event,
payload?): Promise<void>

Emits an event to all targets matching the given target.

Type Parameter
T
ParameterTypeDescription
targetstring | EventTargetLabel of the target Window/Webview/WebviewWindow or raw EventTarget object.
eventstringEvent name. Must include only alphanumeric characters, -, /, : and _.
payload?TEvent payload.

Promise<void>

import { getCurrentWebview } from '@tauri-apps/api/webview';
await getCurrentWebview().emitTo('main', 'webview-loaded', { loggedIn: true, token: 'authToken' });

Source: undefined

hide(): Promise<void>

Hide the webview.

Promise<void>

A promise indicating the success or failure of the operation.

import { getCurrentWebview } from '@tauri-apps/api/webview';
await getCurrentWebview().hide();

Source: undefined

listen<T>(event, handler): Promise<UnlistenFn>

Listen to an emitted event on this webview.

Type Parameter
T
ParameterTypeDescription
eventEventNameEvent name. Must include only alphanumeric characters, -, /, : and _.
handlerEventCallback<T>Event handler.

Promise<UnlistenFn>

A promise resolving to a function to unlisten to the event. Note that removing the listener is required if your listener goes out of scope e.g. the component is unmounted.

import { getCurrentWebview } from '@tauri-apps/api/webview';
const unlisten = await getCurrentWebview().listen<string>('state-changed', (event) => {
console.log(`Got error: ${payload}`);
});
// you need to call unlisten if your handler goes out of scope e.g. the component is unmounted
unlisten();

Source: undefined

onDragDropEvent(handler): Promise<UnlistenFn>

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.

ParameterType
handlerEventCallback<DragDropEvent>

Promise<UnlistenFn>

A promise resolving to a function to unlisten to the event. Note that removing the listener is required if your listener goes out of scope e.g. the component is unmounted.

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');
}
});
// you need to call unlisten if 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.

Source: undefined

once<T>(event, handler): Promise<UnlistenFn>

Listen to an emitted event on this webview only once.

Type Parameter
T
ParameterTypeDescription
eventEventNameEvent name. Must include only alphanumeric characters, -, /, : and _.
handlerEventCallback<T>Event handler.

Promise<UnlistenFn>

A promise resolving to a function to unlisten to the event. Note that removing the listener is required if your listener goes out of scope e.g. the component is unmounted.

import { getCurrentWebview } from '@tauri-apps/api/webview';
const unlisten = await getCurrent().once<null>('initialized', (event) => {
console.log(`Webview initialized!`);
});
// you need to call unlisten if your handler goes out of scope e.g. the component is unmounted
unlisten();

Source: undefined

position(): Promise<PhysicalPosition>

The position of the top-left hand corner of the webview’s client area relative to the top-left hand corner of the desktop.

Promise<PhysicalPosition>

The webview’s position.

import { getCurrentWebview } from '@tauri-apps/api/webview';
const position = await getCurrentWebview().position();

Source: undefined

reparent(window): Promise<void>

Moves this webview to the given label.

ParameterType
windowstring | Window | WebviewWindow

Promise<void>

A promise indicating the success or failure of the operation.

import { getCurrentWebview } from '@tauri-apps/api/webview';
await getCurrentWebview().reparent('other-window');

Source: undefined

setAutoResize(autoResize): Promise<void>

Sets whether the webview should automatically grow and shrink its size and position when the parent window resizes.

ParameterType
autoResizeboolean

Promise<void>

A promise indicating the success or failure of the operation.

import { getCurrentWebview } from '@tauri-apps/api/webview';
await getCurrentWebview().setAutoResize(true);

Source: undefined

setBackgroundColor(color): Promise<void>

Specify the webview background color.

  • 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
ParameterType
colornull | Color

Promise<void>

A promise indicating the success or failure of the operation.

2.1.0

Source: undefined

setFocus(): Promise<void>

Bring the webview to front and focus.

Promise<void>

A promise indicating the success or failure of the operation.

import { getCurrentWebview } from '@tauri-apps/api/webview';
await getCurrentWebview().setFocus();

Source: undefined

setPosition(position): Promise<void>

Sets the webview position.

ParameterTypeDescription
positionLogicalPosition | PhysicalPosition | PositionThe new position, in logical or physical pixels.

Promise<void>

A promise indicating the success or failure of the operation.

import { getCurrent, LogicalPosition } from '@tauri-apps/api/webview';
await getCurrentWebview().setPosition(new LogicalPosition(600, 500));

Source: undefined

setSize(size): Promise<void>

Resizes the webview.

ParameterTypeDescription
sizeLogicalSize | PhysicalSize | SizeThe logical or physical size.

Promise<void>

A promise indicating the success or failure of the operation.

import { getCurrent, LogicalSize } from '@tauri-apps/api/webview';
await getCurrentWebview().setSize(new LogicalSize(600, 500));

Source: undefined

setZoom(scaleFactor): Promise<void>

Set webview zoom level.

ParameterType
scaleFactornumber

Promise<void>

A promise indicating the success or failure of the operation.

import { getCurrentWebview } from '@tauri-apps/api/webview';
await getCurrentWebview().setZoom(1.5);

Source: undefined

show(): Promise<void>

Show the webview.

Promise<void>

A promise indicating the success or failure of the operation.

import { getCurrentWebview } from '@tauri-apps/api/webview';
await getCurrentWebview().show();

Source: undefined

size(): Promise<PhysicalSize>

The physical size of the webview’s client area. The client area is the content of the webview, excluding the title bar and borders.

Promise<PhysicalSize>

The webview’s size.

import { getCurrentWebview } from '@tauri-apps/api/webview';
const size = await getCurrentWebview().size();

Source: undefined

static getAll(): Promise<Webview[]>

Gets a list of instances of Webview for all available webviews.

Promise<Webview[]>

Source: undefined

static getByLabel(label): Promise<null | Webview>

Gets the Webview for the webview associated with the given label.

ParameterTypeDescription
labelstringThe webview label.

Promise<null | Webview>

The Webview instance to communicate with the webview or null if the webview doesn’t exist.

import { Webview } from '@tauri-apps/api/webview';
const mainWebview = Webview.getByLabel('main');

Source: undefined

static getCurrent(): Webview

Get an instance of Webview for the current webview.

Webview

Source: undefined

Configuration for the webview to create.

2.0.0

PropertyTypeDescriptionDefined in
acceptFirstMouse?booleanWhether clicking an inactive webview also clicks through to the webview on macOS.Source: undefined
allowLinkPreview?booleanon 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.allowsLinkPreviewSource: undefined
backgroundColor?ColorSet 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.0Source: undefined
backgroundThrottling?BackgroundThrottlingPolicyChange 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.0Source: undefined
devtools?booleanWhether 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.0Source: undefined
disableInputAccessoryView?booleanAllows 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.Source: undefined
dragDropEnabled?booleanWhether 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.Source: undefined
focus?booleanWhether the webview should have focus or not Since 2.1.0Source: undefined
heightnumberThe initial height.Source: undefined
incognito?booleanWhether or not the webview should be launched in incognito mode. Platform-specific - Android: Unsupported.Source: undefined
javascriptDisabled?booleanWhether we should disable JavaScript code execution on the webview or not.Source: undefined
proxyUrl?stringThe 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+.Source: undefined
transparent?booleanWhether 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.Source: undefined
url?stringRemote 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).Source: undefined
useHttpsScheme?booleanSets 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.0Source: undefined
userAgent?stringThe user agent for the webview.Source: undefined
widthnumberThe initial width.Source: undefined
xnumberThe initial vertical position.Source: undefined
ynumberThe initial horizontal position.Source: undefined
zoomHotkeysEnabled?booleanWhether page zooming by hotkeys is enabled Platform-specific: - Windows: Controls WebView2’s 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.Source: undefined

type Color: [number, number, number] | [number, number, number, number] | object | string;

An RGBA color. Each value has minimum of 0 and maximum of 255.

It can be either a string #ffffff, an array of 3 or 4 elements or an object.

2.0.0

Source: undefined


type DragDropEvent: object | object | object | object;

The drag and drop event types.

Source: undefined

function getAllWebviews(): Promise<Webview[]>

Gets a list of instances of Webview for all available webviews.

Promise<Webview[]>

2.0.0

Source: undefined


function getCurrentWebview(): Webview

Get an instance of Webview for the current webview.

Webview

2.0.0

Source: undefined


Tauri v2.8 中文网 - 粤ICP备13048890号
Nodejs.cn 旗下网站