File size: 23,015 Bytes
adb87a5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 | /**
* 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 }) => { });
* ```
*
* @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 { type EventTarget } from './event';
import { BackgroundThrottlingPolicy, ScrollBarStyle, Color, Window } from './window';
import { WebviewWindow } from './webviewWindow';
/** The drag and drop event types. */
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
*/
declare function getCurrentWebview(): Webview;
/**
* Gets a list of instances of `Webview` for all available webviews.
*
* @since 2.0.0
*/
declare function getAllWebviews(): Promise<Webview[]>;
/** @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 `_`.
*
* @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
*/
declare 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. */
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-/:_`.
* @returns The {@link Webview} instance to communicate with the webview.
*/
constructor(window: Window, label: WebviewLabel, options: WebviewOptions);
/**
* 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 getByLabel(label: string): Promise<Webview | null>;
/**
* Get an instance of `Webview` for the current webview.
*/
static getCurrent(): Webview;
/**
* Gets a list of instances of `Webview` for all available webviews.
*/
static getAll(): Promise<Webview[]>;
/**
* 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}`);
* });
*
* // you need to call unlisten if 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.
* Note that removing the listener is required if your listener goes out of scope e.g. the component is unmounted.
*/
listen<T>(event: EventName, handler: EventCallback<T>): Promise<UnlistenFn>;
/**
* Listen to an emitted event on this webview only once.
*
* @example
* ```typescript
* 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();
* ```
*
* @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.
* Note that removing the listener is required if your listener goes out of scope e.g. the component is unmounted.
*/
once<T>(event: EventName, handler: EventCallback<T>): Promise<UnlistenFn>;
/**
* 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.
*/
emit<T>(event: string, payload?: T): Promise<void>;
/**
* 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.
*/
emitTo<T>(target: string | EventTarget, event: string, payload?: T): Promise<void>;
/** @ignore */
_handleTauriEvent<T>(event: string, handler: EventCallback<T>): boolean;
/**
* 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.
*/
position(): Promise<PhysicalPosition>;
/**
* 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.
*/
size(): Promise<PhysicalSize>;
/**
* 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.
*/
close(): Promise<void>;
/**
* Resizes the webview.
* @example
* ```typescript
* import { getCurrent, LogicalSize } from '@tauri-apps/api/webview';
* 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.
*/
setSize(size: LogicalSize | PhysicalSize | Size): Promise<void>;
/**
* Sets the webview position.
* @example
* ```typescript
* import { getCurrent, LogicalPosition } from '@tauri-apps/api/webview';
* await getCurrentWebview().setPosition(new LogicalPosition(600, 500));
* ```
*
* @param position The new position, in logical or physical pixels.
* @returns A promise indicating the success or failure of the operation.
*/
setPosition(position: LogicalPosition | PhysicalPosition | Position): Promise<void>;
/**
* 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.
*/
setFocus(): Promise<void>;
/**
* 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.
*/
setAutoResize(autoResize: boolean): Promise<void>;
/**
* 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.
*/
hide(): Promise<void>;
/**
* 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.
*/
show(): Promise<void>;
/**
* Set webview zoom level.
* @example
* ```typescript
* import { getCurrentWebview } from '@tauri-apps/api/webview';
* await getCurrentWebview().setZoom(1.5);
* ```
*
* @returns A promise indicating the success or failure of the operation.
*/
setZoom(scaleFactor: number): Promise<void>;
/**
* Moves this webview to the given label.
* @example
* ```typescript
* import { getCurrentWebview } from '@tauri-apps/api/webview';
* await getCurrentWebview().reparent('other-window');
* ```
*
* @returns A promise indicating the success or failure of the operation.
*/
reparent(window: Window | WebviewWindow | string): Promise<void>;
/**
* Clears all browsing data for this webview.
* @example
* ```typescript
* import { getCurrentWebview } from '@tauri-apps/api/webview';
* await getCurrentWebview().clearAllBrowsingData();
* ```
*
* @returns A promise indicating the success or failure of the operation.
*/
clearAllBrowsingData(): Promise<void>;
/**
* Specify the webview background color.
*
* #### Platfrom-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`
*
* @returns A promise indicating the success or failure of the operation.
*
* @since 2.1.0
*/
setBackgroundColor(color: Color | null): Promise<void>;
/**
* 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');
* }
* });
*
* // 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.
*
* @returns 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.
*/
onDragDropEvent(handler: EventCallback<DragDropEvent>): Promise<UnlistenFn>;
}
/**
* 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 vertical position in logical pixels. */
x: number;
/** The initial horizontal position in logical pixels. */
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;
}
export { Webview, getCurrentWebview, getAllWebviews };
export type { DragDropEvent, WebviewOptions, Color };
|