tauri/webview/webview_window.rs
1// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
2// SPDX-License-Identifier: Apache-2.0
3// SPDX-License-Identifier: MIT
4
5//! [`Window`] that hosts a single [`Webview`].
6
7use std::{
8 borrow::Cow,
9 path::{Path, PathBuf},
10 sync::{Arc, MutexGuard},
11};
12
13use crate::{
14 Emitter, EventName, Listener, ResourceTable, Window,
15 event::EventTarget,
16 ipc::ScopeObject,
17 runtime::dpi::{PhysicalPosition, PhysicalSize, Position, Size},
18 webview::{NewWindowResponse, ScrollBarStyle},
19 window::Monitor,
20};
21#[cfg(desktop)]
22use crate::{
23 image::Image,
24 menu::{ContextMenu, Menu},
25 runtime::{UserAttentionType, window::CursorIcon},
26};
27use tauri_runtime::webview::NewWindowFeatures;
28use tauri_utils::config::{BackgroundThrottlingPolicy, Color, WebviewUrl, WindowConfig};
29use url::Url;
30
31use crate::{
32 AppHandle, Event, EventId, Manager, Runtime, Webview, WindowEvent,
33 ipc::{CommandArg, CommandItem, InvokeError, OwnedInvokeResponder},
34 manager::AppManager,
35 sealed::{ManagerBase, RuntimeOrDispatch},
36 webview::{Cookie, PageLoadPayload, WebviewBuilder, WebviewEvent},
37 window::WindowBuilder,
38};
39
40use tauri_macros::default_runtime;
41
42#[cfg(windows)]
43use windows::Win32::Foundation::HWND;
44
45use super::{DownloadEvent, ResolvedScope};
46
47/// A builder for [`WebviewWindow`], a window that hosts a single webview.
48pub struct WebviewWindowBuilder<'a, R: Runtime, M: Manager<R>> {
49 window_builder: WindowBuilder<'a, R, M>,
50 webview_builder: WebviewBuilder<R>,
51}
52
53impl<'a, R: Runtime, M: Manager<R>> WebviewWindowBuilder<'a, R, M> {
54 /// Initializes a webview window builder with the given window label.
55 ///
56 /// # Known issues
57 ///
58 /// On Windows, this function deadlocks when used in a synchronous command and event handlers, see [the Webview2 issue].
59 /// You should use `async` commands and separate threads when creating windows.
60 ///
61 /// # Examples
62 ///
63 /// - Create a window in the setup hook:
64 ///
65 /// ```
66 /// tauri::Builder::default()
67 /// .setup(|app| {
68 /// let webview_window = tauri::WebviewWindowBuilder::new(app, "label", tauri::WebviewUrl::App("index.html".into()))
69 /// .build()?;
70 /// Ok(())
71 /// });
72 /// ```
73 ///
74 /// - Create a window in a separate thread:
75 ///
76 /// ```
77 /// tauri::Builder::default()
78 /// .setup(|app| {
79 /// let handle = app.handle().clone();
80 /// std::thread::spawn(move || {
81 /// let webview_window = tauri::WebviewWindowBuilder::new(&handle, "label", tauri::WebviewUrl::App("index.html".into()))
82 /// .build()
83 /// .unwrap();
84 /// });
85 /// Ok(())
86 /// });
87 /// ```
88 ///
89 /// - Create a window in a command:
90 ///
91 /// ```
92 /// #[tauri::command]
93 /// async fn create_window(app: tauri::AppHandle) {
94 /// let webview_window = tauri::WebviewWindowBuilder::new(&app, "label", tauri::WebviewUrl::App("index.html".into()))
95 /// .build()
96 /// .unwrap();
97 /// }
98 /// ```
99 ///
100 /// [the Webview2 issue]: https://github.com/tauri-apps/wry/issues/583
101 pub fn new<L: Into<String>>(manager: &'a M, label: L, url: WebviewUrl) -> Self {
102 let label = label.into();
103 Self {
104 window_builder: WindowBuilder::new(manager, &label),
105 webview_builder: WebviewBuilder::new(&label, url),
106 }
107 }
108
109 /// Initializes a webview window builder from a [`WindowConfig`] from tauri.conf.json.
110 /// Keep in mind that you can't create 2 windows with the same `label` so make sure
111 /// that the initial window was closed or change the label of the cloned [`WindowConfig`].
112 ///
113 /// # Known issues
114 ///
115 /// On Windows, this function deadlocks when used in a synchronous command or event handlers, see [the Webview2 issue].
116 /// You should use `async` commands and separate threads when creating windows.
117 ///
118 /// # Examples
119 ///
120 /// - Create a window in a command:
121 ///
122 /// ```
123 /// #[tauri::command]
124 /// async fn reopen_window(app: tauri::AppHandle) {
125 /// let webview_window = tauri::WebviewWindowBuilder::from_config(&app, &app.config().app.windows.get(0).unwrap())
126 /// .unwrap()
127 /// .build()
128 /// .unwrap();
129 /// }
130 /// ```
131 ///
132 /// - Create a window in a command from a config with a specific label, and change its label so multiple instances can exist:
133 ///
134 /// ```
135 /// #[tauri::command]
136 /// async fn open_window_multiple(app: tauri::AppHandle) {
137 /// let mut conf = app.config().app.windows.iter().find(|c| c.label == "template-for-multiwindow").unwrap().clone();
138 /// // This should be a unique label for all windows. For example, we can use a random suffix:
139 /// let mut buf = [0u8; 1];
140 /// assert_eq!(getrandom::fill(&mut buf), Ok(()));
141 /// conf.label = format!("my-multiwindow-{}", buf[0]);
142 /// let webview_window = tauri::WebviewWindowBuilder::from_config(&app, &conf)
143 /// .unwrap()
144 /// .build()
145 /// .unwrap();
146 /// }
147 /// ```
148 ///
149 /// [the Webview2 issue]: https://github.com/tauri-apps/wry/issues/583
150 pub fn from_config(manager: &'a M, config: &WindowConfig) -> crate::Result<Self> {
151 Ok(Self {
152 window_builder: WindowBuilder::from_config(manager, config)?,
153 webview_builder: WebviewBuilder::from_config(config),
154 })
155 }
156
157 /// Registers a global menu event listener.
158 ///
159 /// Note that this handler is called for any menu event,
160 /// whether it is coming from this window, another window or from the tray icon menu.
161 ///
162 /// Also note that this handler will not be called if
163 /// the window used to register it was closed.
164 ///
165 /// # Examples
166 /// ```
167 /// use tauri::menu::{Menu, Submenu, MenuItem};
168 /// tauri::Builder::default()
169 /// .setup(|app| {
170 /// let handle = app.handle();
171 /// let save_menu_item = MenuItem::new(handle, "Save", true, None::<&str>)?;
172 /// let menu = Menu::with_items(handle, &[
173 /// &Submenu::with_items(handle, "File", true, &[
174 /// &save_menu_item,
175 /// ])?,
176 /// ])?;
177 /// let webview_window = tauri::WebviewWindowBuilder::new(app, "editor", tauri::WebviewUrl::App("index.html".into()))
178 /// .menu(menu)
179 /// .on_menu_event(move |window, event| {
180 /// if event.id == save_menu_item.id() {
181 /// // save menu item
182 /// }
183 /// })
184 /// .build()
185 /// .unwrap();
186 ///
187 /// Ok(())
188 /// });
189 /// ```
190 #[cfg(desktop)]
191 pub fn on_menu_event<F: Fn(&crate::Window<R>, crate::menu::MenuEvent) + Send + Sync + 'static>(
192 mut self,
193 f: F,
194 ) -> Self {
195 self.window_builder = self.window_builder.on_menu_event(f);
196 self
197 }
198
199 /// Defines a closure to be executed when the webview makes an HTTP request for a web resource, allowing you to modify the response.
200 ///
201 /// Currently only implemented for the `tauri` URI protocol.
202 ///
203 /// **NOTE:** Currently this is **not** executed when using external URLs such as a development server,
204 /// but it might be implemented in the future. **Always** check the request URL.
205 ///
206 /// # Examples
207 /// ```rust,no_run
208 /// use tauri::{
209 /// utils::config::{Csp, CspDirectiveSources, WebviewUrl},
210 /// webview::WebviewWindowBuilder,
211 /// };
212 /// use http::header::HeaderValue;
213 /// use std::collections::HashMap;
214 /// tauri::Builder::default()
215 /// .setup(|app| {
216 /// let webview_window = WebviewWindowBuilder::new(app, "core", WebviewUrl::App("index.html".into()))
217 /// .on_web_resource_request(|request, response| {
218 /// if request.uri().scheme_str() == Some("tauri") {
219 /// // if we have a CSP header, Tauri is loading an HTML file
220 /// // for this example, let's dynamically change the CSP
221 /// if let Some(csp) = response.headers_mut().get_mut("Content-Security-Policy") {
222 /// // use the tauri helper to parse the CSP policy to a map
223 /// let mut csp_map: HashMap<String, CspDirectiveSources> = Csp::Policy(csp.to_str().unwrap().to_string()).into();
224 /// csp_map.entry("script-src".to_string()).or_insert_with(Default::default).push("'unsafe-inline'");
225 /// // use the tauri helper to get a CSP string from the map
226 /// let csp_string = Csp::from(csp_map).to_string();
227 /// *csp = HeaderValue::from_str(&csp_string).unwrap();
228 /// }
229 /// }
230 /// })
231 /// .build()?;
232 /// Ok(())
233 /// });
234 /// ```
235 pub fn on_web_resource_request<
236 F: Fn(http::Request<Vec<u8>>, &mut http::Response<Cow<'static, [u8]>>) + Send + Sync + 'static,
237 >(
238 mut self,
239 f: F,
240 ) -> Self {
241 self.webview_builder = self.webview_builder.on_web_resource_request(f);
242 self
243 }
244
245 /// Defines a closure to be executed when the webview navigates to a URL. Returning `false` cancels the navigation.
246 ///
247 /// # Examples
248 /// ```rust,no_run
249 /// use tauri::{
250 /// utils::config::{Csp, CspDirectiveSources, WebviewUrl},
251 /// webview::WebviewWindowBuilder,
252 /// };
253 /// use http::header::HeaderValue;
254 /// use std::collections::HashMap;
255 /// tauri::Builder::default()
256 /// .setup(|app| {
257 /// let webview_window = WebviewWindowBuilder::new(app, "core", WebviewUrl::App("index.html".into()))
258 /// .on_navigation(|url| {
259 /// // allow the production URL or localhost on dev
260 /// url.scheme() == "tauri" || (cfg!(dev) && url.host_str() == Some("localhost"))
261 /// })
262 /// .build()?;
263 /// Ok(())
264 /// });
265 /// ```
266 pub fn on_navigation<F: Fn(&Url) -> bool + Send + 'static>(mut self, f: F) -> Self {
267 self.webview_builder = self.webview_builder.on_navigation(f);
268 self
269 }
270
271 /// Set a new window request handler to decide if incoming url is allowed to be opened.
272 ///
273 /// A new window is requested to be opened by the [window.open] API.
274 ///
275 /// The closure take the URL to open and the window features object and returns [`NewWindowResponse`] to determine whether the window should open.
276 ///
277 /// # Examples
278 /// ```rust,no_run
279 /// use tauri::{
280 /// utils::config::WebviewUrl,
281 /// webview::WebviewWindowBuilder,
282 /// };
283 /// use http::header::HeaderValue;
284 /// use std::collections::HashMap;
285 /// tauri::Builder::default()
286 /// .setup(|app| {
287 /// let app_ = app.handle().clone();
288 /// let webview_window = WebviewWindowBuilder::new(app, "core", WebviewUrl::App("index.html".into()))
289 /// .on_new_window(move |url, features| {
290 /// let builder = tauri::WebviewWindowBuilder::new(
291 /// &app_,
292 /// // note: add an ID counter or random label generator to support multiple opened windows at the same time
293 /// "opened-window",
294 /// tauri::WebviewUrl::External("about:blank".parse().unwrap()),
295 /// )
296 /// .window_features(features)
297 /// .on_document_title_changed(|window, title| {
298 /// window.set_title(&title).unwrap();
299 /// })
300 /// .title(url.as_str());
301 ///
302 /// let window = builder.build().unwrap();
303 /// tauri::webview::NewWindowResponse::Create { window }
304 /// })
305 /// .build()?;
306 /// Ok(())
307 /// });
308 /// ```
309 ///
310 /// # Platform-specific
311 ///
312 /// - **Android / iOS**: Not supported.
313 ///
314 /// [window.open]: https://developer.mozilla.org/en-US/docs/Web/API/Window/open
315 pub fn on_new_window<F: Fn(Url, NewWindowFeatures) -> NewWindowResponse<R> + Send + 'static>(
316 mut self,
317 f: F,
318 ) -> Self {
319 self.webview_builder = self.webview_builder.on_new_window(f);
320 self
321 }
322
323 /// Defines a closure to be executed when the document title changes.
324 ///
325 /// Note that it may run before or after the navigation event.
326 pub fn on_document_title_changed<F: Fn(WebviewWindow<R>, String) + Send + 'static>(
327 mut self,
328 f: F,
329 ) -> Self {
330 self.webview_builder = self
331 .webview_builder
332 .on_document_title_changed(move |webview, url| {
333 f(
334 WebviewWindow {
335 window: webview.window(),
336 webview,
337 },
338 url,
339 )
340 });
341 self
342 }
343
344 /// Set a download event handler to be notified when a download is requested or finished.
345 ///
346 /// Returning `false` prevents the download from happening on a [`DownloadEvent::Requested`] event.
347 ///
348 /// # Examples
349 ///
350 #[cfg_attr(
351 feature = "unstable",
352 doc = r####"
353```rust,no_run
354use tauri::{
355 utils::config::{Csp, CspDirectiveSources, WebviewUrl},
356 webview::{DownloadEvent, WebviewWindowBuilder},
357};
358
359tauri::Builder::default()
360 .setup(|app| {
361 let handle = app.handle();
362 let webview_window = WebviewWindowBuilder::new(handle, "core", WebviewUrl::App("index.html".into()))
363 .on_download(|webview, event| {
364 match event {
365 DownloadEvent::Requested { url, destination } => {
366 println!("downloading {}", url);
367 *destination = "/home/tauri/target/path".into();
368 }
369 DownloadEvent::Finished { url, path, success } => {
370 println!("downloaded {} to {:?}, success: {}", url, path, success);
371 }
372 _ => (),
373 }
374 // let the download start
375 true
376 })
377 .build()?;
378
379 Ok(())
380 });
381```
382 "####
383 )]
384 pub fn on_download<F: Fn(Webview<R>, DownloadEvent<'_>) -> bool + Send + Sync + 'static>(
385 mut self,
386 f: F,
387 ) -> Self {
388 self.webview_builder.download_handler.replace(Arc::new(f));
389 self
390 }
391
392 /// Defines a closure to be executed when a page load event is triggered.
393 /// The event can be either [`tauri_runtime::webview::PageLoadEvent::Started`] if the page has started loading
394 /// or [`tauri_runtime::webview::PageLoadEvent::Finished`] when the page finishes loading.
395 ///
396 /// # Examples
397 /// ```rust,no_run
398 /// use tauri::{
399 /// utils::config::{Csp, CspDirectiveSources, WebviewUrl},
400 /// webview::{PageLoadEvent, WebviewWindowBuilder},
401 /// };
402 /// use http::header::HeaderValue;
403 /// use std::collections::HashMap;
404 /// tauri::Builder::default()
405 /// .setup(|app| {
406 /// let webview_window = WebviewWindowBuilder::new(app, "core", WebviewUrl::App("index.html".into()))
407 /// .on_page_load(|window, payload| {
408 /// match payload.event() {
409 /// PageLoadEvent::Started => {
410 /// println!("{} finished loading", payload.url());
411 /// }
412 /// PageLoadEvent::Finished => {
413 /// println!("{} finished loading", payload.url());
414 /// }
415 /// }
416 /// })
417 /// .build()?;
418 /// Ok(())
419 /// });
420 /// ```
421 pub fn on_page_load<F: Fn(WebviewWindow<R>, PageLoadPayload<'_>) + Send + Sync + 'static>(
422 mut self,
423 f: F,
424 ) -> Self {
425 self.webview_builder = self.webview_builder.on_page_load(move |webview, payload| {
426 f(
427 WebviewWindow {
428 window: webview.window(),
429 webview,
430 },
431 payload,
432 )
433 });
434 self
435 }
436
437 /// Defines a closure to be executed when a permission is requested.
438 ///
439 /// The handler receives the [`crate::webview::PermissionKind`] and should return
440 /// the desired [`crate::webview::PermissionResponse`].
441 ///
442 /// > [!NOTE]
443 /// > This handler only triggers for new permission requests. If the user has already
444 /// > allowed or denied a permission persistently within the webview, the browser
445 /// > will use the saved preference instead of calling this handler.
446 ///
447 /// ## Platform-specific:
448 ///
449 /// - **Windows**: Fully supported via WebView2's PermissionRequested event.
450 /// - **macOS / iOS**: Fully supported via WKUIDelegate's requestMediaCapturePermission.
451 /// - **Linux**: Fully supported via WebKitGTK's permission-request signal.
452 /// - **Android**: Supported via JNI bridge for geolocation, microphone, camera,
453 /// protected media, and MIDI requests. Android runtime permissions may still
454 /// trigger native OS prompts before access is granted.
455 ///
456 /// # Examples
457 ///
458 /// ```rust,no_run
459 /// use tauri::{
460 /// webview::{PermissionKind, PermissionResponse, WebviewWindowBuilder},
461 /// WebviewUrl,
462 /// };
463 /// tauri::Builder::default()
464 /// .setup(|app| {
465 /// WebviewWindowBuilder::new(app, "core", WebviewUrl::App("index.html".into()))
466 /// .on_permission_request(|_, kind| match kind {
467 /// PermissionKind::Geolocation => PermissionResponse::Allow,
468 /// PermissionKind::Notifications => PermissionResponse::Allow,
469 /// _ => PermissionResponse::Default,
470 /// })
471 /// .build()?;
472 /// Ok(())
473 /// });
474 /// ```
475 pub fn on_permission_request<
476 F: Fn(Webview<R>, crate::webview::PermissionKind) -> crate::webview::PermissionResponse
477 + Send
478 + Sync
479 + 'static,
480 >(
481 mut self,
482 f: F,
483 ) -> Self {
484 self.webview_builder = self.webview_builder.on_permission_request(f);
485 self
486 }
487
488 /// Creates a new window.
489 pub fn build(self) -> crate::Result<WebviewWindow<R>> {
490 let (window, webview) = self.window_builder.with_webview(self.webview_builder)?;
491 Ok(WebviewWindow { window, webview })
492 }
493}
494
495/// Desktop APIs.
496#[cfg(desktop)]
497impl<'a, R: Runtime, M: Manager<R>> WebviewWindowBuilder<'a, R, M> {
498 /// Sets the menu for the window.
499 #[must_use]
500 pub fn menu(mut self, menu: crate::menu::Menu<R>) -> Self {
501 self.window_builder = self.window_builder.menu(menu);
502 self
503 }
504
505 /// Show window in the center of the screen.
506 #[must_use]
507 pub fn center(mut self) -> Self {
508 self.window_builder = self.window_builder.center();
509 self
510 }
511
512 /// Prevent the window from overflowing the working area (e.g. monitor size - taskbar size)
513 /// on creation, which means the window size will be limited to `monitor size - taskbar size`
514 ///
515 /// **NOTE**: The overflow check is only performed on window creation, resizes can still overflow
516 ///
517 /// ## Platform-specific
518 ///
519 /// - **iOS / Android:** Unsupported.
520 #[must_use]
521 pub fn prevent_overflow(mut self) -> Self {
522 self.window_builder = self.window_builder.prevent_overflow();
523 self
524 }
525
526 /// Prevent the window from overflowing the working area (e.g. monitor size - taskbar size)
527 /// on creation with a margin, which means the window size will be limited to `monitor size - taskbar size - margin size`
528 ///
529 /// **NOTE**: The overflow check is only performed on window creation, resizes can still overflow
530 ///
531 /// ## Platform-specific
532 ///
533 /// - **iOS / Android:** Unsupported.
534 #[must_use]
535 pub fn prevent_overflow_with_margin(mut self, margin: impl Into<Size>) -> Self {
536 self.window_builder = self.window_builder.prevent_overflow_with_margin(margin);
537 self
538 }
539
540 /// Whether the window's native maximize button is enabled or not.
541 /// If resizable is set to false, this setting is ignored.
542 ///
543 /// ## Platform-specific
544 ///
545 /// - **macOS:** Disables the "zoom" button in the window titlebar, which is also used to enter fullscreen mode.
546 /// - **Linux / iOS / Android:** Unsupported.
547 #[must_use]
548 pub fn maximizable(mut self, maximizable: bool) -> Self {
549 self.window_builder = self.window_builder.maximizable(maximizable);
550 self
551 }
552
553 /// Whether the window's native minimize button is enabled or not.
554 ///
555 /// ## Platform-specific
556 ///
557 /// - **Linux / iOS / Android:** Unsupported.
558 #[must_use]
559 pub fn minimizable(mut self, minimizable: bool) -> Self {
560 self.window_builder = self.window_builder.minimizable(minimizable);
561 self
562 }
563
564 /// Whether the window's native close button is enabled or not.
565 ///
566 /// ## Platform-specific
567 ///
568 /// - **Linux:** "GTK+ will do its best to convince the window manager not to show a close button.
569 /// Depending on the system, this function may not have any effect when called on a window that is already visible"
570 /// - **iOS / Android:** Unsupported.
571 #[must_use]
572 pub fn closable(mut self, closable: bool) -> Self {
573 self.window_builder = self.window_builder.closable(closable);
574 self
575 }
576
577 /// Whether to start the window in fullscreen or not.
578 #[must_use]
579 pub fn fullscreen(mut self, fullscreen: bool) -> Self {
580 self.window_builder = self.window_builder.fullscreen(fullscreen);
581 self
582 }
583
584 /// Whether the window will be initially focused or not.
585 #[must_use]
586 pub fn focused(mut self, focused: bool) -> Self {
587 self.window_builder = self.window_builder.focused(focused);
588 self.webview_builder = self.webview_builder.focused(focused);
589 self
590 }
591
592 /// Whether the window should be maximized upon creation.
593 #[must_use]
594 pub fn maximized(mut self, maximized: bool) -> Self {
595 self.window_builder = self.window_builder.maximized(maximized);
596 self
597 }
598
599 /// Whether the window should have borders and bars.
600 #[must_use]
601 pub fn decorations(mut self, decorations: bool) -> Self {
602 self.window_builder = self.window_builder.decorations(decorations);
603 self
604 }
605
606 /// Whether the window should always be below other windows.
607 #[must_use]
608 pub fn always_on_bottom(mut self, always_on_bottom: bool) -> Self {
609 self.window_builder = self.window_builder.always_on_bottom(always_on_bottom);
610 self
611 }
612
613 /// Whether the window should always be on top of other windows.
614 #[must_use]
615 pub fn always_on_top(mut self, always_on_top: bool) -> Self {
616 self.window_builder = self.window_builder.always_on_top(always_on_top);
617 self
618 }
619
620 /// Whether the window will be visible on all workspaces or virtual desktops.
621 #[must_use]
622 pub fn visible_on_all_workspaces(mut self, visible_on_all_workspaces: bool) -> Self {
623 self.window_builder = self
624 .window_builder
625 .visible_on_all_workspaces(visible_on_all_workspaces);
626 self
627 }
628
629 /// Sets the window icon.
630 pub fn icon(mut self, icon: Image<'a>) -> crate::Result<Self> {
631 self.window_builder = self.window_builder.icon(icon)?;
632 Ok(self)
633 }
634
635 /// Sets whether or not the window icon should be hidden from the taskbar.
636 ///
637 /// ## Platform-specific
638 ///
639 /// - **macOS**: Unsupported.
640 #[must_use]
641 pub fn skip_taskbar(mut self, skip: bool) -> Self {
642 self.window_builder = self.window_builder.skip_taskbar(skip);
643 self
644 }
645
646 /// Sets custom name for Windows' window class. **Windows only**.
647 #[must_use]
648 pub fn window_classname<S: Into<String>>(mut self, classname: S) -> Self {
649 self.window_builder = self.window_builder.window_classname(classname);
650 self
651 }
652
653 /// This sets `WS_EX_NOREDIRECTIONBITMAP`.
654 ///
655 /// This can avoid the white flash that may appear before the webview content is rendered
656 /// when using a transparent window. **Windows only**.
657 #[must_use]
658 pub fn no_redirection_bitmap(mut self, enable: bool) -> Self {
659 self.window_builder = self.window_builder.no_redirection_bitmap(enable);
660 self
661 }
662
663 /// Sets whether or not the window has shadow.
664 ///
665 /// ## Platform-specific
666 ///
667 /// - **Windows:**
668 /// - `false` has no effect on decorated window, shadows are always ON.
669 /// - `true` will make undecorated window have a 1px white border,
670 /// and on Windows 11, it will have a rounded corners.
671 /// - **Linux:** Unsupported.
672 #[must_use]
673 pub fn shadow(mut self, enable: bool) -> Self {
674 self.window_builder = self.window_builder.shadow(enable);
675 self
676 }
677
678 /// Sets a parent to the window to be created.
679 ///
680 /// ## Platform-specific
681 ///
682 /// - **Windows**: This sets the passed parent as an owner window to the window to be created.
683 /// From [MSDN owned windows docs](https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#owned-windows):
684 /// - An owned window is always above its owner in the z-order.
685 /// - The system automatically destroys an owned window when its owner is destroyed.
686 /// - An owned window is hidden when its owner is minimized.
687 /// - **Linux**: This makes the new window transient for parent, see <https://docs.gtk.org/gtk3/method.Window.set_transient_for.html>
688 /// - **macOS**: This adds the window as a child of parent, see <https://developer.apple.com/documentation/appkit/nswindow/1419152-addchildwindow?language=objc>
689 pub fn parent(mut self, parent: &WebviewWindow<R>) -> crate::Result<Self> {
690 self.window_builder = self.window_builder.parent(&parent.window)?;
691 Ok(self)
692 }
693
694 /// Set an owner to the window to be created.
695 ///
696 /// From MSDN:
697 /// - An owned window is always above its owner in the z-order.
698 /// - The system automatically destroys an owned window when its owner is destroyed.
699 /// - An owned window is hidden when its owner is minimized.
700 ///
701 /// For more information, see <https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#owned-windows>
702 #[cfg(windows)]
703 pub fn owner(mut self, owner: &WebviewWindow<R>) -> crate::Result<Self> {
704 self.window_builder = self.window_builder.owner(&owner.window)?;
705 Ok(self)
706 }
707
708 /// Set an owner to the window to be created.
709 ///
710 /// From MSDN:
711 /// - An owned window is always above its owner in the z-order.
712 /// - The system automatically destroys an owned window when its owner is destroyed.
713 /// - An owned window is hidden when its owner is minimized.
714 ///
715 /// For more information, see <https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#owned-windows>
716 #[cfg(windows)]
717 #[must_use]
718 pub fn owner_raw(mut self, owner: HWND) -> Self {
719 self.window_builder = self.window_builder.owner_raw(owner);
720 self
721 }
722
723 /// Sets a parent to the window to be created.
724 ///
725 /// A child window has the WS_CHILD style and is confined to the client area of its parent window.
726 ///
727 /// For more information, see <https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#child-windows>
728 #[cfg(windows)]
729 #[must_use]
730 pub fn parent_raw(mut self, parent: HWND) -> Self {
731 self.window_builder = self.window_builder.parent_raw(parent);
732 self
733 }
734
735 /// Sets a parent to the window to be created.
736 ///
737 /// See <https://developer.apple.com/documentation/appkit/nswindow/1419152-addchildwindow?language=objc>
738 #[cfg(target_os = "macos")]
739 #[must_use]
740 pub fn parent_raw(mut self, parent: *mut std::ffi::c_void) -> Self {
741 self.window_builder = self.window_builder.parent_raw(parent);
742 self
743 }
744
745 /// Sets the window to be created transient for parent.
746 ///
747 /// See <https://docs.gtk.org/gtk3/method.Window.set_transient_for.html>
748 #[cfg(any(
749 target_os = "linux",
750 target_os = "dragonfly",
751 target_os = "freebsd",
752 target_os = "netbsd",
753 target_os = "openbsd"
754 ))]
755 pub fn transient_for(mut self, parent: &WebviewWindow<R>) -> crate::Result<Self> {
756 self.window_builder = self.window_builder.transient_for(&parent.window)?;
757 Ok(self)
758 }
759
760 /// Sets the window to be created transient for parent.
761 ///
762 /// See <https://docs.gtk.org/gtk3/method.Window.set_transient_for.html>
763 #[cfg(any(
764 target_os = "linux",
765 target_os = "dragonfly",
766 target_os = "freebsd",
767 target_os = "netbsd",
768 target_os = "openbsd"
769 ))]
770 #[must_use]
771 pub fn transient_for_raw(mut self, parent: &impl gtk::glib::IsA<gtk::Window>) -> Self {
772 self.window_builder = self.window_builder.transient_for_raw(parent);
773 self
774 }
775
776 /// Enables or disables drag and drop support of this window.
777 ///
778 /// Note: this is a different config from [`Self::disable_drag_drop_handler`]
779 #[cfg(windows)]
780 #[must_use]
781 pub fn drag_and_drop(mut self, enabled: bool) -> Self {
782 self.window_builder = self.window_builder.drag_and_drop(enabled);
783 self
784 }
785
786 /// Sets the [`crate::TitleBarStyle`].
787 #[cfg(target_os = "macos")]
788 #[must_use]
789 pub fn title_bar_style(mut self, style: crate::TitleBarStyle) -> Self {
790 self.window_builder = self.window_builder.title_bar_style(style);
791 self
792 }
793
794 /// Change the position of the window controls on macOS.
795 ///
796 /// Requires titleBarStyle: Overlay and decorations: true.
797 #[cfg(target_os = "macos")]
798 #[must_use]
799 pub fn traffic_light_position<P: Into<Position>>(mut self, position: P) -> Self {
800 self.webview_builder.webview_attributes = self
801 .webview_builder
802 .webview_attributes
803 .traffic_light_position(position.into());
804 self
805 }
806
807 /// Whether to show a link preview when long pressing on links. Available on macOS and iOS only.
808 ///
809 /// Default is true.
810 ///
811 /// See https://docs.rs/objc2-web-kit/latest/objc2_web_kit/struct.WKWebView.html#method.allowsLinkPreview
812 ///
813 /// ## Platform-specific
814 ///
815 /// - **Linux / Windows / Android:** Unsupported.
816 #[cfg(target_os = "macos")]
817 #[must_use]
818 pub fn allow_link_preview(mut self, allow_link_preview: bool) -> Self {
819 self.webview_builder = self.webview_builder.allow_link_preview(allow_link_preview);
820 self
821 }
822
823 /// Hide the window title.
824 #[cfg(target_os = "macos")]
825 #[must_use]
826 pub fn hidden_title(mut self, hidden: bool) -> Self {
827 self.window_builder = self.window_builder.hidden_title(hidden);
828 self
829 }
830
831 /// Defines the window [tabbing identifier] for macOS.
832 ///
833 /// Windows with matching tabbing identifiers will be grouped together.
834 /// If the tabbing identifier is not set, automatic tabbing will be disabled.
835 ///
836 /// [tabbing identifier]: <https://developer.apple.com/documentation/appkit/nswindow/1644704-tabbingidentifier>
837 #[cfg(target_os = "macos")]
838 #[must_use]
839 pub fn tabbing_identifier(mut self, identifier: &str) -> Self {
840 self.window_builder = self.window_builder.tabbing_identifier(identifier);
841 self
842 }
843
844 /// Sets window effects.
845 ///
846 /// Requires the window to be transparent.
847 ///
848 /// ## Platform-specific:
849 ///
850 /// - **Windows**: If using decorations or shadows, you may want to try this workaround <https://github.com/tauri-apps/tao/issues/72#issuecomment-975607891>
851 /// - **Linux**: Unsupported
852 pub fn effects(mut self, effects: crate::utils::config::WindowEffectsConfig) -> Self {
853 self.window_builder = self.window_builder.effects(effects);
854 self
855 }
856}
857
858/// Window APIs.
859impl<'a, R: Runtime, M: Manager<R>> WebviewWindowBuilder<'a, R, M> {
860 /// The initial position of the window in logical pixels.
861 #[must_use]
862 pub fn position(mut self, x: f64, y: f64) -> Self {
863 self.window_builder = self.window_builder.position(x, y);
864 self
865 }
866
867 /// Window size in logical pixels.
868 #[must_use]
869 pub fn inner_size(mut self, width: f64, height: f64) -> Self {
870 self.window_builder = self.window_builder.inner_size(width, height);
871 self
872 }
873
874 /// Window min inner size in logical pixels.
875 #[must_use]
876 pub fn min_inner_size(mut self, min_width: f64, min_height: f64) -> Self {
877 self.window_builder = self.window_builder.min_inner_size(min_width, min_height);
878 self
879 }
880
881 /// Window max inner size in logical pixels.
882 #[must_use]
883 pub fn max_inner_size(mut self, max_width: f64, max_height: f64) -> Self {
884 self.window_builder = self.window_builder.max_inner_size(max_width, max_height);
885 self
886 }
887
888 /// Window inner size constraints.
889 #[must_use]
890 pub fn inner_size_constraints(
891 mut self,
892 constraints: tauri_runtime::window::WindowSizeConstraints,
893 ) -> Self {
894 self.window_builder = self.window_builder.inner_size_constraints(constraints);
895 self
896 }
897
898 /// Whether the window is resizable or not.
899 /// When resizable is set to false, native window's maximize button is automatically disabled.
900 #[must_use]
901 pub fn resizable(mut self, resizable: bool) -> Self {
902 self.window_builder = self.window_builder.resizable(resizable);
903 self
904 }
905
906 /// The title of the window in the title bar.
907 #[must_use]
908 pub fn title<S: Into<String>>(mut self, title: S) -> Self {
909 self.window_builder = self.window_builder.title(title);
910 self
911 }
912
913 /// Sets the window to be initially focused.
914 #[must_use]
915 #[deprecated(
916 since = "1.2.0",
917 note = "The window is automatically focused by default. This function Will be removed in 3.0.0. Use `focused` instead."
918 )]
919 pub fn focus(mut self) -> Self {
920 self.window_builder = self.window_builder.focused(true);
921 self.webview_builder = self.webview_builder.focused(true);
922 self
923 }
924
925 /// Whether the window will be focusable or not.
926 #[must_use]
927 pub fn focusable(mut self, focusable: bool) -> Self {
928 self.window_builder = self.window_builder.focusable(focusable);
929 self
930 }
931
932 /// Whether the window should be immediately visible upon creation.
933 #[must_use]
934 pub fn visible(mut self, visible: bool) -> Self {
935 self.window_builder = self.window_builder.visible(visible);
936 self
937 }
938
939 /// Forces a theme or uses the system settings if None was provided.
940 ///
941 /// ## Platform-specific
942 ///
943 /// - **macOS**: Only supported on macOS 10.14+.
944 #[must_use]
945 pub fn theme(mut self, theme: Option<crate::Theme>) -> Self {
946 self.window_builder = self.window_builder.theme(theme);
947 self
948 }
949
950 /// Prevents the window contents from being captured by other apps.
951 #[must_use]
952 pub fn content_protected(mut self, protected: bool) -> Self {
953 self.window_builder = self.window_builder.content_protected(protected);
954 self
955 }
956}
957
958/// Webview attributes.
959impl<R: Runtime, M: Manager<R>> WebviewWindowBuilder<'_, R, M> {
960 /// Sets whether clicking an inactive window also clicks through to the webview.
961 #[must_use]
962 pub fn accept_first_mouse(mut self, accept: bool) -> Self {
963 self.webview_builder = self.webview_builder.accept_first_mouse(accept);
964 self
965 }
966
967 /// Adds the provided JavaScript to a list of scripts that should be run after the global object has been created,
968 /// but before the HTML document has been parsed and before any other script included by the HTML document is run.
969 ///
970 /// Since it runs on all top-level document navigations,
971 /// it's recommended to check the `window.location` to guard your script from running on unexpected origins.
972 ///
973 /// This is executed only on the main frame.
974 /// If you only want to run it in all frames, use [Self::initialization_script_for_all_frames] instead.
975 ///
976 /// ## Platform-specific
977 ///
978 /// - **Windows:** scripts are always added to subframes.
979 /// - **Android:** When [addDocumentStartJavaScript] is not supported,
980 /// we prepend initialization scripts to each HTML head (implementation only supported on custom protocol URLs).
981 /// For remote URLs, we use [onPageStarted] which is not guaranteed to run before other scripts.
982 ///
983 /// # Examples
984 ///
985 /// ```rust
986 /// const INIT_SCRIPT: &str = r#"
987 /// if (window.location.origin === 'https://tauri.app') {
988 /// console.log("hello world from js init script");
989 ///
990 /// window.__MY_CUSTOM_PROPERTY__ = { foo: 'bar' };
991 /// }
992 /// "#;
993 ///
994 /// fn main() {
995 /// tauri::Builder::default()
996 /// .setup(|app| {
997 /// let webview = tauri::WebviewWindowBuilder::new(app, "label", tauri::WebviewUrl::App("index.html".into()))
998 /// .initialization_script(INIT_SCRIPT)
999 /// .build()?;
1000 /// Ok(())
1001 /// });
1002 /// }
1003 /// ```
1004 ///
1005 /// [addDocumentStartJavaScript]: https://developer.android.com/reference/androidx/webkit/WebViewCompat#addDocumentStartJavaScript(android.webkit.WebView,java.lang.String,java.util.Set%3Cjava.lang.String%3E)
1006 /// [onPageStarted]: https://developer.android.com/reference/android/webkit/WebViewClient#onPageStarted(android.webkit.WebView,%20java.lang.String,%20android.graphics.Bitmap)
1007 #[must_use]
1008 pub fn initialization_script(mut self, script: impl Into<String>) -> Self {
1009 self.webview_builder = self.webview_builder.initialization_script(script);
1010 self
1011 }
1012
1013 /// Adds the provided JavaScript to a list of scripts that should be run after the global object has been created,
1014 /// but before the HTML document has been parsed and before any other script included by the HTML document is run.
1015 ///
1016 /// Since it runs on all top-level document navigations and also child frame page navigations,
1017 /// it's recommended to check the `window.location` to guard your script from running on unexpected origins.
1018 ///
1019 /// This is executed on all frames (main frame and also sub frames).
1020 /// If you only want to run the script in the main frame, use [Self::initialization_script] instead.
1021 ///
1022 /// ## Platform-specific
1023 ///
1024 /// - **Android:** When [addDocumentStartJavaScript] is not supported,
1025 /// we prepend initialization scripts to each HTML head (implementation only supported on custom protocol URLs).
1026 /// For remote URLs, we use [onPageStarted] which is not guaranteed to run before other scripts.
1027 ///
1028 /// # Examples
1029 ///
1030 /// ```rust
1031 /// const INIT_SCRIPT: &str = r#"
1032 /// if (window.location.origin === 'https://tauri.app') {
1033 /// console.log("hello world from js init script");
1034 ///
1035 /// window.__MY_CUSTOM_PROPERTY__ = { foo: 'bar' };
1036 /// }
1037 /// "#;
1038 ///
1039 /// fn main() {
1040 /// tauri::Builder::default()
1041 /// .setup(|app| {
1042 /// let webview = tauri::WebviewWindowBuilder::new(app, "label", tauri::WebviewUrl::App("index.html".into()))
1043 /// .initialization_script_for_all_frames(INIT_SCRIPT)
1044 /// .build()?;
1045 /// Ok(())
1046 /// });
1047 /// }
1048 /// ```
1049 ///
1050 /// [addDocumentStartJavaScript]: https://developer.android.com/reference/androidx/webkit/WebViewCompat#addDocumentStartJavaScript(android.webkit.WebView,java.lang.String,java.util.Set%3Cjava.lang.String%3E)
1051 /// [onPageStarted]: https://developer.android.com/reference/android/webkit/WebViewClient#onPageStarted(android.webkit.WebView,%20java.lang.String,%20android.graphics.Bitmap)
1052 #[must_use]
1053 pub fn initialization_script_for_all_frames(mut self, script: impl Into<String>) -> Self {
1054 self.webview_builder = self
1055 .webview_builder
1056 .initialization_script_for_all_frames(script);
1057 self
1058 }
1059
1060 /// Set the user agent for the webview
1061 #[must_use]
1062 pub fn user_agent(mut self, user_agent: &str) -> Self {
1063 self.webview_builder = self.webview_builder.user_agent(user_agent);
1064 self
1065 }
1066
1067 /// Set additional arguments for the webview.
1068 ///
1069 /// ## Platform-specific
1070 ///
1071 /// - **macOS / Linux / Android / iOS**: Unsupported.
1072 ///
1073 /// ## Warning
1074 ///
1075 /// Webview instances with different browser arguments must also have different [data directories](Self::data_directory).
1076 ///
1077 /// By default wry passes `--disable-features=msWebOOUI,msPdfOOUI,msSmartScreenProtection`
1078 /// so if you use this method, you also need to disable these components by yourself if you want.
1079 #[must_use]
1080 pub fn additional_browser_args(mut self, additional_args: &str) -> Self {
1081 self.webview_builder = self
1082 .webview_builder
1083 .additional_browser_args(additional_args);
1084 self
1085 }
1086
1087 /// Data directory for the webview.
1088 #[must_use]
1089 pub fn data_directory(mut self, data_directory: PathBuf) -> Self {
1090 self.webview_builder = self.webview_builder.data_directory(data_directory);
1091 self
1092 }
1093
1094 /// Disables the webview drag and drop handler used internally to generate [`DragDropEvent`](crate::DragDropEvent)s.
1095 ///
1096 /// This is required to use HTML5 drag and drop APIs on the frontend on Windows since we replace the drag drop handler of WebView2.
1097 #[must_use]
1098 pub fn disable_drag_drop_handler(mut self) -> Self {
1099 self.webview_builder = self.webview_builder.disable_drag_drop_handler();
1100 self
1101 }
1102
1103 /// Enables clipboard access for the page rendered on **Linux** and **Windows**.
1104 ///
1105 /// **macOS** doesn't provide such method and is always enabled by default,
1106 /// but you still need to add menu item accelerators to use shortcuts.
1107 #[must_use]
1108 pub fn enable_clipboard_access(mut self) -> Self {
1109 self.webview_builder = self.webview_builder.enable_clipboard_access();
1110 self
1111 }
1112
1113 /// Enable or disable incognito mode for the WebView..
1114 ///
1115 /// ## Platform-specific:
1116 ///
1117 /// **Android**: Unsupported.
1118 #[must_use]
1119 pub fn incognito(mut self, incognito: bool) -> Self {
1120 self.webview_builder = self.webview_builder.incognito(incognito);
1121 self
1122 }
1123
1124 /// Sets the webview to automatically grow and shrink its size and position when the parent window resizes.
1125 #[must_use]
1126 pub fn auto_resize(mut self) -> Self {
1127 self.webview_builder = self.webview_builder.auto_resize();
1128 self
1129 }
1130
1131 /// Set a proxy URL for the WebView for all network requests.
1132 ///
1133 /// Must be either a `http://` or a `socks5://` URL.
1134 #[must_use]
1135 pub fn proxy_url(mut self, url: Url) -> Self {
1136 self.webview_builder = self.webview_builder.proxy_url(url);
1137 self
1138 }
1139
1140 /// Whether the window should be transparent. If this is true, writing colors
1141 /// with alpha values different than `1.0` will produce a transparent window.
1142 ///
1143 /// On Windows, using `no_redirection_bitmap` can help avoid a white flash when
1144 /// creating a transparent window.
1145 #[cfg(any(not(target_os = "macos"), feature = "macos-private-api"))]
1146 #[cfg_attr(
1147 docsrs,
1148 doc(cfg(any(not(target_os = "macos"), feature = "macos-private-api")))
1149 )]
1150 #[must_use]
1151 pub fn transparent(mut self, transparent: bool) -> Self {
1152 #[cfg(desktop)]
1153 {
1154 self.window_builder = self.window_builder.transparent(transparent);
1155 }
1156 self.webview_builder = self.webview_builder.transparent(transparent);
1157 self
1158 }
1159
1160 /// Whether page zooming by hotkeys and mousewheel should be enabled or not.
1161 ///
1162 /// ## Platform-specific:
1163 ///
1164 /// - **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.
1165 /// - **MacOS / Linux**: Injects a polyfill that zooms in and out with `Ctrl/Cmd + [- = +]` hotkeys or mousewheel events,
1166 /// 20% in each step, ranging from 20% to 1000%. Requires `core:webview:allow-set-webview-zoom` permission
1167 ///
1168 /// - **Android / iOS**: Unsupported.
1169 #[must_use]
1170 pub fn zoom_hotkeys_enabled(mut self, enabled: bool) -> Self {
1171 self.webview_builder = self.webview_builder.zoom_hotkeys_enabled(enabled);
1172 self
1173 }
1174
1175 /// Whether browser extensions can be installed for the webview process
1176 ///
1177 /// ## Platform-specific:
1178 ///
1179 /// - **Windows**: Enables the WebView2 environment's [`AreBrowserExtensionsEnabled`](https://learn.microsoft.com/en-us/microsoft-edge/webview2/reference/winrt/microsoft_web_webview2_core/corewebview2environmentoptions?view=webview2-winrt-1.0.2739.15#arebrowserextensionsenabled)
1180 /// - **MacOS / Linux / iOS / Android** - Unsupported.
1181 #[must_use]
1182 pub fn browser_extensions_enabled(mut self, enabled: bool) -> Self {
1183 self.webview_builder = self.webview_builder.browser_extensions_enabled(enabled);
1184 self
1185 }
1186
1187 /// Set the path from which to load extensions from. Extensions stored in this path should be unpacked Chrome extensions on Windows, and compiled `.so` extensions on Linux.
1188 ///
1189 /// ## Platform-specific:
1190 ///
1191 /// - **Windows**: Browser extensions must first be enabled. See [`browser_extensions_enabled`](Self::browser_extensions_enabled)
1192 /// - **MacOS / iOS / Android** - Unsupported.
1193 #[must_use]
1194 pub fn extensions_path(mut self, path: impl AsRef<Path>) -> Self {
1195 self.webview_builder = self.webview_builder.extensions_path(path);
1196 self
1197 }
1198
1199 /// Initialize the WebView with a custom data store identifier.
1200 /// Can be used as a replacement for data_directory not being available in WKWebView.
1201 ///
1202 /// - **macOS / iOS**: Available on macOS >= 14 and iOS >= 17
1203 /// - **Windows / Linux / Android**: Unsupported.
1204 #[must_use]
1205 pub fn data_store_identifier(mut self, data_store_identifier: [u8; 16]) -> Self {
1206 self.webview_builder = self
1207 .webview_builder
1208 .data_store_identifier(data_store_identifier);
1209 self
1210 }
1211
1212 /// Sets whether the custom protocols should use `https://<scheme>.localhost` instead of the default `http://<scheme>.localhost` on Windows and Android. Defaults to `false`.
1213 ///
1214 /// ## Note
1215 ///
1216 /// 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.
1217 ///
1218 /// ## Warning
1219 ///
1220 /// Changing this value between releases will change the IndexedDB, cookies and localstorage location and your app will not be able to access the old data.
1221 #[must_use]
1222 pub fn use_https_scheme(mut self, enabled: bool) -> Self {
1223 self.webview_builder = self.webview_builder.use_https_scheme(enabled);
1224 self
1225 }
1226
1227 /// Whether web inspector, which is usually called browser devtools, is enabled or not. Enabled by default.
1228 ///
1229 /// This API works in **debug** builds, but requires `devtools` feature flag to enable it in **release** builds.
1230 ///
1231 /// ## Platform-specific
1232 ///
1233 /// - macOS: This will call private functions on **macOS**.
1234 /// - Android: Open `chrome://inspect/#devices` in Chrome to get the devtools window. Wry's `WebView` devtools API isn't supported on Android.
1235 /// - iOS: Open Safari > Develop > [Your Device Name] > [Your WebView] to get the devtools window.
1236 #[must_use]
1237 pub fn devtools(mut self, enabled: bool) -> Self {
1238 self.webview_builder = self.webview_builder.devtools(enabled);
1239 self
1240 }
1241
1242 /// Set the window and webview background color.
1243 ///
1244 /// ## Platform-specific:
1245 ///
1246 /// - **Android / iOS:** Unsupported for the window layer.
1247 /// - **macOS / iOS**: Not implemented for the webview layer.
1248 /// - **Windows**:
1249 /// - alpha channel is ignored for the window layer.
1250 /// - On Windows 7, alpha channel is ignored for the webview layer.
1251 /// - On Windows 8 and newer, if alpha channel is not `0`, it will be ignored.
1252 #[must_use]
1253 pub fn background_color(mut self, color: Color) -> Self {
1254 self.window_builder = self.window_builder.background_color(color);
1255 self.webview_builder = self.webview_builder.background_color(color);
1256 self
1257 }
1258
1259 /// Change the default background throttling behaviour.
1260 ///
1261 /// By default, browsers use a suspend policy that will throttle timers and even unload
1262 /// the whole tab (view) to free resources after roughly 5 minutes when a view became
1263 /// minimized or hidden. This will pause all tasks until the documents visibility state
1264 /// changes back from hidden to visible by bringing the view back to the foreground.
1265 ///
1266 /// ## Platform-specific
1267 ///
1268 /// - **Linux / Windows / Android**: Unsupported. Workarounds like a pending WebLock transaction might suffice.
1269 /// - **iOS**: Supported since version 17.0+.
1270 /// - **macOS**: Supported since version 14.0+.
1271 ///
1272 /// see <https://github.com/tauri-apps/tauri/issues/5250#issuecomment-2569380578>
1273 #[must_use]
1274 pub fn background_throttling(mut self, policy: BackgroundThrottlingPolicy) -> Self {
1275 self.webview_builder = self.webview_builder.background_throttling(policy);
1276 self
1277 }
1278
1279 /// Whether JavaScript should be disabled.
1280 #[must_use]
1281 pub fn disable_javascript(mut self) -> Self {
1282 self.webview_builder = self.webview_builder.disable_javascript();
1283 self
1284 }
1285
1286 /// Specifies the native scrollbar style to use with the webview.
1287 /// CSS styles that modifier the scrollbar are applied on top of the native appearance configured here.
1288 ///
1289 /// Defaults to [`ScrollBarStyle::Default`], which is the browser default.
1290 ///
1291 /// ## Platform-specific
1292 ///
1293 /// - **Windows**:
1294 /// - [`ScrollBarStyle::FluentOverlay`] requires WebView2 Runtime version 125.0.2535.41 or higher,
1295 /// and does nothing on older versions.
1296 /// - This option must be given the same value for all webviews that target the same data directory. Use
1297 /// [`WebviewWindowBuilder::data_directory`] to change data directories if needed.
1298 /// - **Linux / Android / iOS / macOS**: Unsupported. Only supports `Default` and performs no operation.
1299 #[must_use]
1300 pub fn scroll_bar_style(mut self, style: ScrollBarStyle) -> Self {
1301 self.webview_builder = self.webview_builder.scroll_bar_style(style);
1302 self
1303 }
1304
1305 /// Controls the WebView's browser-level general autofill behavior.
1306 ///
1307 /// **This option does not disable password or credit card autofill.**
1308 ///
1309 /// When set to `false`, the WebView will not automatically populate
1310 /// general form fields using previously stored data such as addresses
1311 /// or contact information.
1312 ///
1313 /// By default, this is `true`.
1314 ///
1315 /// ## Platform-specific
1316 ///
1317 /// - **Windows**: Supported. WebView2's autofill feature (called
1318 /// "Suggestions") may not honor `autocomplete="off"` on input
1319 /// elements in some cases.
1320 /// - **Linux / Android / iOS / macOS**: Unsupported and performs no
1321 /// operation.
1322 #[must_use]
1323 pub fn general_autofill_enabled(mut self, enabled: bool) -> Self {
1324 self.webview_builder = self.webview_builder.general_autofill_enabled(enabled);
1325 self
1326 }
1327
1328 /// Allows overriding the keyboard accessory view on iOS.
1329 /// Returning `None` effectively removes the view.
1330 ///
1331 /// The closure parameter is the webview instance.
1332 ///
1333 /// The accessory view is the view that appears above the keyboard when a text input element is focused.
1334 /// It usually displays a view with "Done", "Next" buttons.
1335 ///
1336 /// # Examples
1337 ///
1338 /// ```
1339 /// tauri::Builder::default()
1340 /// .setup(|app| {
1341 /// let mut builder = tauri::WebviewWindowBuilder::new(app, "label", tauri::WebviewUrl::App("index.html".into()));
1342 /// #[cfg(target_os = "ios")]
1343 /// {
1344 /// window_builder = window_builder.with_input_accessory_view_builder(|_webview| unsafe {
1345 /// let mtm = objc2::MainThreadMarker::new_unchecked();
1346 /// let button = objc2_ui_kit::UIButton::buttonWithType(objc2_ui_kit::UIButtonType(1), mtm);
1347 /// button.setTitle_forState(
1348 /// Some(&objc2_foundation::NSString::from_str("Tauri")),
1349 /// objc2_ui_kit::UIControlState(0),
1350 /// );
1351 /// Some(button.downcast().unwrap())
1352 /// });
1353 /// }
1354 /// let webview = builder.build()?;
1355 /// Ok(())
1356 /// });
1357 /// ```
1358 ///
1359 /// # Stability
1360 ///
1361 /// This relies on [`objc2_ui_kit`] which does not provide a stable API yet, so it can receive breaking changes in minor releases.
1362 #[cfg(target_os = "ios")]
1363 pub fn with_input_accessory_view_builder<
1364 F: Fn(&objc2_ui_kit::UIView) -> Option<objc2::rc::Retained<objc2_ui_kit::UIView>>
1365 + Send
1366 + Sync
1367 + 'static,
1368 >(
1369 mut self,
1370 builder: F,
1371 ) -> Self {
1372 self.webview_builder = self
1373 .webview_builder
1374 .with_input_accessory_view_builder(builder);
1375 self
1376 }
1377
1378 /// Whether to limit navigations to App-Bound Domains. This is necessary to
1379 /// enable Service Workers on iOS according to
1380 /// [StackOverflow](https://stackoverflow.com/questions/49673399/service-workers-unavailable-in-wkwebview-in-ios-11-3/64155509#64155509).
1381 ///
1382 /// Default is false.
1383 ///
1384 /// Note: If you pass in `true` make sure to add localhost and any [`registrable
1385 /// domains`](https://developer.mozilla.org/en-US/docs/Glossary/Registrable_domain)
1386 /// used in this webview to tauri-src/Info.ios.plist:
1387 ///
1388 /// ```xml
1389 /// <plist>
1390 /// <dict>
1391 /// <key>WKAppBoundDomains</key>
1392 /// <array>
1393 /// <string>localhost</string>
1394 /// <string>aregistrabledomain.example</string>
1395 /// </array>
1396 /// </dict>
1397 /// </plist>
1398 /// ```
1399 ///
1400 /// You must add `localhost` if any webview with this set to true opens a
1401 /// local webpage, makes any localhost calls, or uses the isolation pattern
1402 /// because Tauri uses the `localhost` domain for hosting the application
1403 /// webpage, the IPC protocol, and the isolation pattern's iframe.
1404 ///
1405 /// Requests served through custom uri schemes are allowed so long as they use
1406 /// a registrable domain specified in the `WKAppBoundDomains` array for all the
1407 /// requests from the app, including requests for the `localhost` domain.
1408 ///
1409 /// In theory, you can whitelist an entire uri scheme by including the
1410 /// protocol name followed by a colon. For example, to allow all requests
1411 /// using a custom "stream" uri scheme (see [this tauri
1412 /// example](https://github.com/tauri-apps/tauri/blob/dev/examples/streaming/main.rs)),
1413 /// you could add `stream:` to the AppBoundDomains array. That said, I'm not
1414 /// sure whether Apple would let your app through app review if you do
1415 /// whitelist an entire protocol because this feature is not mentioned in
1416 /// [their blog post on App-Bound
1417 /// Domains](https://webkit.org/blog/10882/app-bound-domains/).
1418 ///
1419 /// See https://webkit.org/blog/10882/app-bound-domains/ and
1420 /// https://developer.apple.com/documentation/webkit/wkwebviewconfiguration/limitsnavigationstoappbounddomains
1421 /// for the official documentation on App-Bound Domains.
1422 ///
1423 /// ## Platform-specific
1424 ///
1425 /// - **iOS**: Supported since version 14.0+.
1426 /// - **Linux / Windows / Android / MacOS:** Unsupported.
1427 pub fn limit_navigations_to_app_bound_domains(mut self, limit_navigations: bool) -> Self {
1428 self.webview_builder = self
1429 .webview_builder
1430 .limit_navigations_to_app_bound_domains(limit_navigations);
1431 self
1432 }
1433
1434 /// Set the environment for the webview.
1435 /// Useful if you need to share the same environment, for instance when using the [`Self::on_new_window`].
1436 #[cfg(all(feature = "wry", windows))]
1437 pub fn with_environment(
1438 mut self,
1439 environment: webview2_com::Microsoft::Web::WebView2::Win32::ICoreWebView2Environment,
1440 ) -> Self {
1441 self.webview_builder = self.webview_builder.with_environment(environment);
1442 self
1443 }
1444
1445 /// Creates a new webview sharing the same web process with the provided webview.
1446 /// Useful if you need to link a webview to another, for instance when using the [`Self::on_new_window`].
1447 #[cfg(all(
1448 feature = "wry",
1449 any(
1450 target_os = "linux",
1451 target_os = "dragonfly",
1452 target_os = "freebsd",
1453 target_os = "netbsd",
1454 target_os = "openbsd",
1455 )
1456 ))]
1457 pub fn with_related_view(mut self, related_view: webkit2gtk::WebView) -> Self {
1458 self.webview_builder = self.webview_builder.with_related_view(related_view);
1459 self
1460 }
1461
1462 /// Set the webview configuration.
1463 /// Useful if you need to share the same webview configuration, for instance when using the [`Self::on_new_window`].
1464 #[cfg(target_os = "macos")]
1465 pub fn with_webview_configuration(
1466 mut self,
1467 webview_configuration: objc2::rc::Retained<objc2_web_kit::WKWebViewConfiguration>,
1468 ) -> Self {
1469 self.webview_builder = self
1470 .webview_builder
1471 .with_webview_configuration(webview_configuration);
1472 self
1473 }
1474
1475 /// Set the window features.
1476 /// Useful if you need to share the same window features, for instance when using the [`Self::on_new_window`].
1477 #[cfg(any(
1478 target_os = "macos",
1479 windows,
1480 target_os = "linux",
1481 target_os = "dragonfly",
1482 target_os = "freebsd",
1483 target_os = "netbsd",
1484 target_os = "openbsd"
1485 ))]
1486 pub fn window_features(mut self, features: NewWindowFeatures) -> Self {
1487 if let Some(position) = features.position() {
1488 self.window_builder = self.window_builder.position(position.x, position.y);
1489 }
1490
1491 if let Some(size) = features.size() {
1492 self.window_builder = self.window_builder.inner_size(size.width, size.height);
1493 }
1494
1495 #[cfg(target_os = "macos")]
1496 {
1497 self.webview_builder = self
1498 .webview_builder
1499 .with_webview_configuration(features.opener().target_configuration.clone());
1500 }
1501
1502 #[cfg(all(feature = "wry", windows))]
1503 {
1504 self.webview_builder = self
1505 .webview_builder
1506 .with_environment(features.opener().environment.clone());
1507 }
1508
1509 #[cfg(all(
1510 feature = "wry",
1511 any(
1512 target_os = "linux",
1513 target_os = "dragonfly",
1514 target_os = "freebsd",
1515 target_os = "netbsd",
1516 target_os = "openbsd",
1517 )
1518 ))]
1519 {
1520 self.webview_builder = self
1521 .webview_builder
1522 .with_related_view(features.opener().webview.clone());
1523 }
1524 self
1525 }
1526}
1527
1528// Android specific APIs
1529#[cfg(target_os = "android")]
1530impl<R: Runtime, M: Manager<R>> WebviewWindowBuilder<'_, R, M> {
1531 /// The name of the activity to create for this webview window.
1532 pub fn activity_name<S: Into<String>>(mut self, class_name: S) -> Self {
1533 self.window_builder = self.window_builder.activity_name(class_name);
1534 self
1535 }
1536
1537 /// Sets the name of the activity that is creating this webview window.
1538 ///
1539 /// This is important to determine which stack the activity will belong to.
1540 pub fn created_by_activity_name<S: Into<String>>(mut self, class_name: S) -> Self {
1541 self.window_builder = self.window_builder.created_by_activity_name(class_name);
1542 self
1543 }
1544}
1545
1546/// iOS specific APIs
1547#[cfg(target_os = "ios")]
1548impl<R: Runtime, M: Manager<R>> WebviewWindowBuilder<'_, R, M> {
1549 /// Sets the identifier of the scene that is requesting the new scene,
1550 /// establishing a relationship between the two scenes.
1551 ///
1552 /// By default the system uses the foreground scene.
1553 #[cfg(target_os = "ios")]
1554 pub fn requested_by_scene_identifier(mut self, identifier: String) -> Self {
1555 self.window_builder = self
1556 .window_builder
1557 .requested_by_scene_identifier(identifier);
1558 self
1559 }
1560}
1561
1562/// A type that wraps a [`Window`] together with a [`Webview`].
1563#[default_runtime(crate::Wry, wry)]
1564#[derive(Debug)]
1565pub struct WebviewWindow<R: Runtime> {
1566 pub(crate) window: Window<R>,
1567 pub(crate) webview: Webview<R>,
1568}
1569
1570impl<R: Runtime> AsRef<Webview<R>> for WebviewWindow<R> {
1571 fn as_ref(&self) -> &Webview<R> {
1572 &self.webview
1573 }
1574}
1575
1576impl<R: Runtime> Clone for WebviewWindow<R> {
1577 fn clone(&self) -> Self {
1578 Self {
1579 window: self.window.clone(),
1580 webview: self.webview.clone(),
1581 }
1582 }
1583}
1584
1585impl<R: Runtime> Eq for WebviewWindow<R> {}
1586impl<R: Runtime> PartialEq for WebviewWindow<R> {
1587 /// Only use the [`Webview`]'s label to compare equality.
1588 fn eq(&self, other: &Self) -> bool {
1589 self.webview.eq(&other.webview)
1590 }
1591}
1592
1593impl<R: Runtime> raw_window_handle::HasWindowHandle for WebviewWindow<R> {
1594 fn window_handle(
1595 &self,
1596 ) -> std::result::Result<raw_window_handle::WindowHandle<'_>, raw_window_handle::HandleError> {
1597 Ok(unsafe {
1598 raw_window_handle::WindowHandle::borrow_raw(self.window.window_handle()?.as_raw())
1599 })
1600 }
1601}
1602
1603impl<R: Runtime> raw_window_handle::HasDisplayHandle for WebviewWindow<R> {
1604 fn display_handle(
1605 &self,
1606 ) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, raw_window_handle::HandleError> {
1607 self.webview.app_handle.display_handle()
1608 }
1609}
1610
1611impl<'de, R: Runtime> CommandArg<'de, R> for WebviewWindow<R> {
1612 /// Grabs the [`Window`] from the [`CommandItem`]. This will never fail.
1613 fn from_command(command: CommandItem<'de, R>) -> Result<Self, InvokeError> {
1614 let webview = command.message.webview();
1615 let window = webview.window();
1616 if window.is_webview_window() {
1617 return Ok(Self { window, webview });
1618 }
1619
1620 Err(InvokeError::from("current webview is not a WebviewWindow"))
1621 }
1622}
1623
1624/// Base webview window functions.
1625impl<R: Runtime> WebviewWindow<R> {
1626 /// Initializes a [`WebviewWindowBuilder`] with the given window label and webview URL.
1627 ///
1628 /// Data URLs are only supported with the `webview-data-url` feature flag.
1629 pub fn builder<M: Manager<R>, L: Into<String>>(
1630 manager: &M,
1631 label: L,
1632 url: WebviewUrl,
1633 ) -> WebviewWindowBuilder<'_, R, M> {
1634 WebviewWindowBuilder::new(manager, label, url)
1635 }
1636
1637 /// Runs the given closure on the main thread.
1638 pub fn run_on_main_thread<F: FnOnce() + Send + 'static>(&self, f: F) -> crate::Result<()> {
1639 self.webview.run_on_main_thread(f)
1640 }
1641
1642 /// The webview label.
1643 pub fn label(&self) -> &str {
1644 self.webview.label()
1645 }
1646
1647 /// Registers a window event listener.
1648 pub fn on_window_event<F: Fn(&WindowEvent) + Send + 'static>(&self, f: F) {
1649 self.window.on_window_event(f);
1650 }
1651
1652 /// Registers a webview event listener.
1653 pub fn on_webview_event<F: Fn(&WebviewEvent) + Send + 'static>(&self, f: F) {
1654 self.webview.on_webview_event(f);
1655 }
1656
1657 /// Resolves the given command scope for this webview on the currently loaded URL.
1658 ///
1659 /// If the command is not allowed, returns None.
1660 ///
1661 /// If the scope cannot be deserialized to the given type, an error is returned.
1662 ///
1663 /// In a command context this can be directly resolved from the command arguments via [crate::ipc::CommandScope]:
1664 ///
1665 /// ```
1666 /// use tauri::ipc::CommandScope;
1667 ///
1668 /// #[derive(Debug, serde::Deserialize)]
1669 /// struct ScopeType {
1670 /// some_value: String,
1671 /// }
1672 /// #[tauri::command]
1673 /// fn my_command(scope: CommandScope<ScopeType>) {
1674 /// // check scope
1675 /// }
1676 /// ```
1677 ///
1678 /// # Examples
1679 ///
1680 /// ```
1681 /// use tauri::Manager;
1682 ///
1683 /// #[derive(Debug, serde::Deserialize)]
1684 /// struct ScopeType {
1685 /// some_value: String,
1686 /// }
1687 ///
1688 /// tauri::Builder::default()
1689 /// .setup(|app| {
1690 /// let webview = app.get_webview_window("main").unwrap();
1691 /// let scope = webview.resolve_command_scope::<ScopeType>("my-plugin", "read");
1692 /// Ok(())
1693 /// });
1694 /// ```
1695 pub fn resolve_command_scope<T: ScopeObject>(
1696 &self,
1697 plugin: &str,
1698 command: &str,
1699 ) -> crate::Result<Option<ResolvedScope<T>>> {
1700 self.webview.resolve_command_scope(plugin, command)
1701 }
1702}
1703
1704/// Menu APIs
1705#[cfg(desktop)]
1706impl<R: Runtime> WebviewWindow<R> {
1707 /// Registers a global menu event listener.
1708 ///
1709 /// Note that this handler is called for any menu event,
1710 /// whether it is coming from this window, another window or from the tray icon menu.
1711 ///
1712 /// Also note that this handler will not be called if
1713 /// the window used to register it was closed.
1714 ///
1715 /// # Examples
1716 ///
1717 /// ```
1718 /// use tauri::menu::{Menu, Submenu, MenuItem};
1719 /// use tauri::{WebviewWindowBuilder, WebviewUrl};
1720 ///
1721 /// tauri::Builder::default()
1722 /// .setup(|app| {
1723 /// let handle = app.handle();
1724 /// let save_menu_item = MenuItem::new(handle, "Save", true, None::<&str>)?;
1725 /// let menu = Menu::with_items(handle, &[
1726 /// &Submenu::with_items(handle, "File", true, &[
1727 /// &save_menu_item,
1728 /// ])?,
1729 /// ])?;
1730 /// let webview_window = WebviewWindowBuilder::new(app, "editor", WebviewUrl::default())
1731 /// .menu(menu)
1732 /// .build()
1733 /// .unwrap();
1734 ///
1735 /// webview_window.on_menu_event(move |window, event| {
1736 /// if event.id == save_menu_item.id() {
1737 /// // save menu item
1738 /// }
1739 /// });
1740 ///
1741 /// Ok(())
1742 /// });
1743 /// ```
1744 pub fn on_menu_event<F: Fn(&crate::Window<R>, crate::menu::MenuEvent) + Send + Sync + 'static>(
1745 &self,
1746 f: F,
1747 ) {
1748 self.window.on_menu_event(f)
1749 }
1750
1751 /// Returns this window menu.
1752 pub fn menu(&self) -> Option<Menu<R>> {
1753 self.window.menu()
1754 }
1755
1756 /// Sets the window menu and returns the previous one.
1757 ///
1758 /// ## Platform-specific:
1759 ///
1760 /// - **macOS:** Unsupported. The menu on macOS is app-wide and not specific to one
1761 /// window, if you need to set it, use [`AppHandle::set_menu`] instead.
1762 #[cfg_attr(target_os = "macos", allow(unused_variables))]
1763 pub fn set_menu(&self, menu: Menu<R>) -> crate::Result<Option<Menu<R>>> {
1764 self.window.set_menu(menu)
1765 }
1766
1767 /// Removes the window menu and returns it.
1768 ///
1769 /// ## Platform-specific:
1770 ///
1771 /// - **macOS:** Unsupported. The menu on macOS is app-wide and not specific to one
1772 /// window, if you need to remove it, use [`AppHandle::remove_menu`] instead.
1773 pub fn remove_menu(&self) -> crate::Result<Option<Menu<R>>> {
1774 self.window.remove_menu()
1775 }
1776
1777 /// Hides the window menu.
1778 ///
1779 /// ## Platform-specific:
1780 ///
1781 /// - **macOS:** Unsupported.
1782 pub fn hide_menu(&self) -> crate::Result<()> {
1783 self.window.hide_menu()
1784 }
1785
1786 /// Shows the window menu.
1787 ///
1788 /// ## Platform-specific:
1789 ///
1790 /// - **macOS:** Unsupported.
1791 pub fn show_menu(&self) -> crate::Result<()> {
1792 self.window.show_menu()
1793 }
1794
1795 /// Shows the window menu.
1796 ///
1797 /// ## Platform-specific:
1798 ///
1799 /// - **macOS:** Unsupported.
1800 pub fn is_menu_visible(&self) -> crate::Result<bool> {
1801 self.window.is_menu_visible()
1802 }
1803
1804 /// Shows the specified menu as a context menu at the cursor position.
1805 pub fn popup_menu<M: ContextMenu>(&self, menu: &M) -> crate::Result<()> {
1806 self.window.popup_menu(menu)
1807 }
1808
1809 /// Shows the specified menu as a context menu at the specified position.
1810 ///
1811 /// The position is relative to the window's top-left corner.
1812 pub fn popup_menu_at<M: ContextMenu, P: Into<Position>>(
1813 &self,
1814 menu: &M,
1815 position: P,
1816 ) -> crate::Result<()> {
1817 self.window.popup_menu_at(menu, position)
1818 }
1819}
1820
1821/// Window getters.
1822impl<R: Runtime> WebviewWindow<R> {
1823 /// Returns the scale factor that can be used to map logical pixels to physical pixels, and vice versa.
1824 pub fn scale_factor(&self) -> crate::Result<f64> {
1825 self.window.scale_factor()
1826 }
1827
1828 /// Returns the position of the top-left hand corner of the window's client area relative to the top-left hand corner of the desktop.
1829 pub fn inner_position(&self) -> crate::Result<PhysicalPosition<i32>> {
1830 self.window.inner_position()
1831 }
1832
1833 /// Returns the position of the top-left hand corner of the window relative to the top-left hand corner of the desktop.
1834 pub fn outer_position(&self) -> crate::Result<PhysicalPosition<i32>> {
1835 self.window.outer_position()
1836 }
1837
1838 /// Returns the physical size of the window's client area.
1839 ///
1840 /// The client area is the content of the window, excluding the title bar and borders.
1841 pub fn inner_size(&self) -> crate::Result<PhysicalSize<u32>> {
1842 self.window.inner_size()
1843 }
1844
1845 /// Returns the physical size of the entire window.
1846 ///
1847 /// These dimensions include the title bar and borders. If you don't want that (and you usually don't), use inner_size instead.
1848 pub fn outer_size(&self) -> crate::Result<PhysicalSize<u32>> {
1849 self.window.outer_size()
1850 }
1851
1852 /// Gets the window's current fullscreen state.
1853 pub fn is_fullscreen(&self) -> crate::Result<bool> {
1854 self.window.is_fullscreen()
1855 }
1856
1857 /// Gets the window's current minimized state.
1858 pub fn is_minimized(&self) -> crate::Result<bool> {
1859 self.window.is_minimized()
1860 }
1861
1862 /// Gets the window's current maximized state.
1863 pub fn is_maximized(&self) -> crate::Result<bool> {
1864 self.window.is_maximized()
1865 }
1866
1867 /// Gets the window's current focus state.
1868 pub fn is_focused(&self) -> crate::Result<bool> {
1869 self.window.is_focused()
1870 }
1871
1872 /// Gets the window's current decoration state.
1873 pub fn is_decorated(&self) -> crate::Result<bool> {
1874 self.window.is_decorated()
1875 }
1876
1877 /// Gets the window's current resizable state.
1878 pub fn is_resizable(&self) -> crate::Result<bool> {
1879 self.window.is_resizable()
1880 }
1881
1882 /// Whether the window is enabled or disabled.
1883 pub fn is_enabled(&self) -> crate::Result<bool> {
1884 self.webview.window().is_enabled()
1885 }
1886
1887 /// Determines if this window should always be on top of other windows.
1888 ///
1889 /// ## Platform-specific
1890 ///
1891 /// - **iOS / Android:** Unsupported.
1892 pub fn is_always_on_top(&self) -> crate::Result<bool> {
1893 self.webview.window().is_always_on_top()
1894 }
1895
1896 /// Gets the window's native maximize button state
1897 ///
1898 /// ## Platform-specific
1899 ///
1900 /// - **Linux / iOS / Android:** Unsupported.
1901 pub fn is_maximizable(&self) -> crate::Result<bool> {
1902 self.window.is_maximizable()
1903 }
1904
1905 /// Gets the window's native minimize button state
1906 ///
1907 /// ## Platform-specific
1908 ///
1909 /// - **Linux / iOS / Android:** Unsupported.
1910 pub fn is_minimizable(&self) -> crate::Result<bool> {
1911 self.window.is_minimizable()
1912 }
1913
1914 /// Gets the window's native close button state
1915 ///
1916 /// ## Platform-specific
1917 ///
1918 /// - **Linux / iOS / Android:** Unsupported.
1919 pub fn is_closable(&self) -> crate::Result<bool> {
1920 self.window.is_closable()
1921 }
1922
1923 /// Gets the window's current visibility state.
1924 pub fn is_visible(&self) -> crate::Result<bool> {
1925 self.window.is_visible()
1926 }
1927
1928 /// Gets the window's current title.
1929 pub fn title(&self) -> crate::Result<String> {
1930 self.window.title()
1931 }
1932
1933 /// Returns the monitor on which the window currently resides.
1934 ///
1935 /// Returns None if current monitor can't be detected.
1936 pub fn current_monitor(&self) -> crate::Result<Option<Monitor>> {
1937 self.window.current_monitor()
1938 }
1939
1940 /// Returns the primary monitor of the system.
1941 ///
1942 /// Returns None if it can't identify any monitor as a primary one.
1943 pub fn primary_monitor(&self) -> crate::Result<Option<Monitor>> {
1944 self.window.primary_monitor()
1945 }
1946
1947 /// Returns the monitor that contains the given point.
1948 pub fn monitor_from_point(&self, x: f64, y: f64) -> crate::Result<Option<Monitor>> {
1949 self.window.monitor_from_point(x, y)
1950 }
1951
1952 /// Returns the list of all the monitors available on the system.
1953 pub fn available_monitors(&self) -> crate::Result<Vec<Monitor>> {
1954 self.window.available_monitors()
1955 }
1956
1957 /// Returns the native handle that is used by this window.
1958 #[cfg(target_os = "macos")]
1959 pub fn ns_window(&self) -> crate::Result<*mut std::ffi::c_void> {
1960 self.window.ns_window()
1961 }
1962
1963 /// Returns the pointer to the content view of this window.
1964 #[cfg(target_os = "macos")]
1965 pub fn ns_view(&self) -> crate::Result<*mut std::ffi::c_void> {
1966 self.window.ns_view()
1967 }
1968
1969 /// Returns the native handle that is used by this window.
1970 #[cfg(windows)]
1971 pub fn hwnd(&self) -> crate::Result<HWND> {
1972 self.window.hwnd()
1973 }
1974
1975 /// Returns the `ApplicationWindow` from gtk crate that is used by this window.
1976 ///
1977 /// Note that this type can only be used on the main thread.
1978 #[cfg(any(
1979 target_os = "linux",
1980 target_os = "dragonfly",
1981 target_os = "freebsd",
1982 target_os = "netbsd",
1983 target_os = "openbsd"
1984 ))]
1985 pub fn gtk_window(&self) -> crate::Result<gtk::ApplicationWindow> {
1986 self.window.gtk_window()
1987 }
1988
1989 /// Returns the vertical [`gtk::Box`] that is added by default as the sole child of this window.
1990 ///
1991 /// Note that this type can only be used on the main thread.
1992 #[cfg(any(
1993 target_os = "linux",
1994 target_os = "dragonfly",
1995 target_os = "freebsd",
1996 target_os = "netbsd",
1997 target_os = "openbsd"
1998 ))]
1999 pub fn default_vbox(&self) -> crate::Result<gtk::Box> {
2000 self.window.default_vbox()
2001 }
2002
2003 /// Returns the name of the Android activity associated with this window.
2004 #[cfg(target_os = "android")]
2005 pub fn activity_name(&self) -> crate::Result<String> {
2006 self.window.activity_name()
2007 }
2008
2009 /// Returns the current window theme.
2010 ///
2011 /// ## Platform-specific
2012 ///
2013 /// - **macOS**: Only supported on macOS 10.14+.
2014 pub fn theme(&self) -> crate::Result<crate::Theme> {
2015 self.window.theme()
2016 }
2017}
2018
2019/// Desktop window getters.
2020#[cfg(desktop)]
2021impl<R: Runtime> WebviewWindow<R> {
2022 /// Get the cursor position relative to the top-left hand corner of the desktop.
2023 ///
2024 /// Note that the top-left hand corner of the desktop is not necessarily the same as the screen.
2025 /// If the user uses a desktop with multiple monitors,
2026 /// the top-left hand corner of the desktop is the top-left hand corner of the main monitor on Windows and macOS
2027 /// or the top-left of the leftmost monitor on X11.
2028 ///
2029 /// The coordinates can be negative if the top-left hand corner of the window is outside of the visible screen region.
2030 pub fn cursor_position(&self) -> crate::Result<PhysicalPosition<f64>> {
2031 self.webview.cursor_position()
2032 }
2033}
2034
2035/// Desktop window setters and actions.
2036#[cfg(desktop)]
2037impl<R: Runtime> WebviewWindow<R> {
2038 /// Centers the window.
2039 pub fn center(&self) -> crate::Result<()> {
2040 self.window.center()
2041 }
2042
2043 /// Requests user attention to the window, this has no effect if the application
2044 /// is already focused. How requesting for user attention manifests is platform dependent,
2045 /// see `UserAttentionType` for details.
2046 ///
2047 /// Providing `None` will unset the request for user attention. Unsetting the request for
2048 /// user attention might not be done automatically by the WM when the window receives input.
2049 ///
2050 /// ## Platform-specific
2051 ///
2052 /// - **macOS:** `None` has no effect.
2053 /// - **Linux:** Urgency levels have the same effect.
2054 pub fn request_user_attention(
2055 &self,
2056 request_type: Option<UserAttentionType>,
2057 ) -> crate::Result<()> {
2058 self.window.request_user_attention(request_type)
2059 }
2060
2061 /// Determines if this window's native maximize button should be enabled.
2062 /// If resizable is set to false, this setting is ignored.
2063 ///
2064 /// ## Platform-specific
2065 ///
2066 /// - **macOS:** Disables the "zoom" button in the window titlebar, which is also used to enter fullscreen mode.
2067 /// - **Linux / iOS / Android:** Unsupported.
2068 pub fn set_maximizable(&self, maximizable: bool) -> crate::Result<()> {
2069 self.window.set_maximizable(maximizable)
2070 }
2071
2072 /// Determines if this window's native minimize button should be enabled.
2073 ///
2074 /// ## Platform-specific
2075 ///
2076 /// - **Linux / iOS / Android:** Unsupported.
2077 pub fn set_minimizable(&self, minimizable: bool) -> crate::Result<()> {
2078 self.window.set_minimizable(minimizable)
2079 }
2080
2081 /// Determines if this window's native close button should be enabled.
2082 ///
2083 /// ## Platform-specific
2084 ///
2085 /// - **Linux:** "GTK+ will do its best to convince the window manager not to show a close button.
2086 /// Depending on the system, this function may not have any effect when called on a window that is already visible"
2087 /// - **iOS / Android:** Unsupported.
2088 pub fn set_closable(&self, closable: bool) -> crate::Result<()> {
2089 self.window.set_closable(closable)
2090 }
2091
2092 /// Maximizes this window.
2093 pub fn maximize(&self) -> crate::Result<()> {
2094 self.window.maximize()
2095 }
2096
2097 /// Un-maximizes this window.
2098 pub fn unmaximize(&self) -> crate::Result<()> {
2099 self.window.unmaximize()
2100 }
2101
2102 /// Minimizes this window.
2103 pub fn minimize(&self) -> crate::Result<()> {
2104 self.window.minimize()
2105 }
2106
2107 /// Un-minimizes this window.
2108 pub fn unminimize(&self) -> crate::Result<()> {
2109 self.window.unminimize()
2110 }
2111
2112 /// Determines if this window should be [decorated].
2113 ///
2114 /// [decorated]: https://en.wikipedia.org/wiki/Window_(computing)#Window_decoration
2115 pub fn set_decorations(&self, decorations: bool) -> crate::Result<()> {
2116 self.window.set_decorations(decorations)
2117 }
2118
2119 /// Determines if this window should have shadow.
2120 ///
2121 /// ## Platform-specific
2122 ///
2123 /// - **Windows:**
2124 /// - `false` has no effect on decorated window, shadow are always ON.
2125 /// - `true` will make undecorated window have a 1px white border,
2126 /// and on Windows 11, it will have a rounded corners.
2127 /// - **Linux:** Unsupported.
2128 pub fn set_shadow(&self, enable: bool) -> crate::Result<()> {
2129 self.window.set_shadow(enable)
2130 }
2131
2132 /// Sets window effects, pass [`None`] to clear any effects applied if possible.
2133 ///
2134 /// Requires the window to be transparent.
2135 ///
2136 /// See [`crate::window::EffectsBuilder`] for a convenient builder for [`crate::utils::config::WindowEffectsConfig`].
2137 ///
2138 ///
2139 /// ```rust,no_run
2140 /// use tauri::{Manager, window::{Color, Effect, EffectState, EffectsBuilder}};
2141 /// tauri::Builder::default()
2142 /// .setup(|app| {
2143 /// let webview_window = app.get_webview_window("main").unwrap();
2144 /// webview_window.set_effects(
2145 /// EffectsBuilder::new()
2146 /// .effect(Effect::Popover)
2147 /// .state(EffectState::Active)
2148 /// .radius(5.)
2149 /// .color(Color(0, 0, 0, 255))
2150 /// .build(),
2151 /// )?;
2152 /// Ok(())
2153 /// });
2154 /// ```
2155 ///
2156 /// ## Platform-specific:
2157 ///
2158 /// - **Windows**: If using decorations or shadows, you may want to try this workaround <https://github.com/tauri-apps/tao/issues/72#issuecomment-975607891>
2159 /// - **Linux**: Unsupported
2160 pub fn set_effects<E: Into<Option<crate::utils::config::WindowEffectsConfig>>>(
2161 &self,
2162 effects: E,
2163 ) -> crate::Result<()> {
2164 self.window.set_effects(effects)
2165 }
2166
2167 /// Determines if this window should always be below other windows.
2168 pub fn set_always_on_bottom(&self, always_on_bottom: bool) -> crate::Result<()> {
2169 self.window.set_always_on_bottom(always_on_bottom)
2170 }
2171
2172 /// Determines if this window should always be on top of other windows.
2173 pub fn set_always_on_top(&self, always_on_top: bool) -> crate::Result<()> {
2174 self.window.set_always_on_top(always_on_top)
2175 }
2176
2177 /// Sets whether the window should be visible on all workspaces or virtual desktops.
2178 pub fn set_visible_on_all_workspaces(
2179 &self,
2180 visible_on_all_workspaces: bool,
2181 ) -> crate::Result<()> {
2182 self
2183 .window
2184 .set_visible_on_all_workspaces(visible_on_all_workspaces)
2185 }
2186
2187 /// Determines if this window should be fullscreen.
2188 pub fn set_fullscreen(&self, fullscreen: bool) -> crate::Result<()> {
2189 self.window.set_fullscreen(fullscreen)
2190 }
2191
2192 /// Sets the window as fullscreen on the monitor that contains the given physical position,
2193 /// such as a [`Monitor::position`](crate::Monitor::position).
2194 ///
2195 /// Does nothing if no monitor contains the position.
2196 pub fn set_fullscreen_on_monitor(&self, position: PhysicalPosition<f64>) -> crate::Result<()> {
2197 self.window.set_fullscreen_on_monitor(position)
2198 }
2199
2200 /// Toggles a fullscreen mode that doesn't require a new macOS space.
2201 /// Returns a boolean indicating whether the transition was successful (this won't work if the window was already in the native fullscreen).
2202 ///
2203 /// This is how fullscreen used to work on macOS in versions before Lion.
2204 /// And allows the user to have a fullscreen window without using another space or taking control over the entire monitor.
2205 ///
2206 /// ## Platform-specific
2207 ///
2208 /// - **macOS:** Uses native simple fullscreen mode.
2209 /// - **Other platforms:** Falls back to [`Self::set_fullscreen`].
2210 pub fn set_simple_fullscreen(&self, enable: bool) -> crate::Result<()> {
2211 self.window.set_simple_fullscreen(enable)
2212 }
2213
2214 /// Sets this window' icon.
2215 pub fn set_icon(&self, icon: Image<'_>) -> crate::Result<()> {
2216 self.window.set_icon(icon)
2217 }
2218
2219 /// Whether to hide the window icon from the taskbar or not.
2220 ///
2221 /// ## Platform-specific
2222 ///
2223 /// - **macOS:** Unsupported.
2224 pub fn set_skip_taskbar(&self, skip: bool) -> crate::Result<()> {
2225 self.window.set_skip_taskbar(skip)
2226 }
2227
2228 /// Grabs the cursor, preventing it from leaving the window.
2229 ///
2230 /// There's no guarantee that the cursor will be hidden. You should
2231 /// hide it by yourself if you want so.
2232 ///
2233 /// ## Platform-specific
2234 ///
2235 /// - **Linux:** Unsupported.
2236 /// - **macOS:** This locks the cursor in a fixed location, which looks visually awkward.
2237 pub fn set_cursor_grab(&self, grab: bool) -> crate::Result<()> {
2238 self.window.set_cursor_grab(grab)
2239 }
2240
2241 /// Modifies the cursor's visibility.
2242 ///
2243 /// If `false`, this will hide the cursor. If `true`, this will show the cursor.
2244 ///
2245 /// ## Platform-specific
2246 ///
2247 /// - **Windows:** The cursor is only hidden within the confines of the window.
2248 /// - **macOS:** The cursor is hidden as long as the window has input focus, even if the cursor is
2249 /// outside of the window.
2250 pub fn set_cursor_visible(&self, visible: bool) -> crate::Result<()> {
2251 self.window.set_cursor_visible(visible)
2252 }
2253
2254 /// Modifies the cursor icon of the window.
2255 pub fn set_cursor_icon(&self, icon: CursorIcon) -> crate::Result<()> {
2256 self.window.set_cursor_icon(icon)
2257 }
2258
2259 /// Changes the position of the cursor in window coordinates.
2260 pub fn set_cursor_position<Pos: Into<Position>>(&self, position: Pos) -> crate::Result<()> {
2261 self.window.set_cursor_position(position)
2262 }
2263
2264 /// Ignores the window cursor events.
2265 pub fn set_ignore_cursor_events(&self, ignore: bool) -> crate::Result<()> {
2266 self.window.set_ignore_cursor_events(ignore)
2267 }
2268
2269 /// Starts dragging the window.
2270 pub fn start_dragging(&self) -> crate::Result<()> {
2271 self.window.start_dragging()
2272 }
2273
2274 /// Sets the overlay icon on the taskbar **Windows only**. Using `None` will remove the icon
2275 ///
2276 /// The overlay icon can be unique for each window.
2277 #[cfg(target_os = "windows")]
2278 #[cfg_attr(docsrs, doc(cfg(target_os = "windows")))]
2279 pub fn set_overlay_icon(&self, icon: Option<Image<'_>>) -> crate::Result<()> {
2280 self.window.set_overlay_icon(icon)
2281 }
2282
2283 /// Sets the taskbar badge count. Using `0` or `None` will remove the badge
2284 ///
2285 /// ## Platform-specific
2286 /// - **Windows:** Unsupported, use [`WebviewWindow::set_overlay_icon`] instead.
2287 /// - **iOS:** iOS expects i32, the value will be clamped to i32::MIN, i32::MAX.
2288 /// - **Android:** Unsupported.
2289 pub fn set_badge_count(&self, count: Option<i64>) -> crate::Result<()> {
2290 self.window.set_badge_count(count)
2291 }
2292
2293 /// Sets the taskbar badge label **macOS only**. Using `None` will remove the badge
2294 #[cfg(target_os = "macos")]
2295 #[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
2296 pub fn set_badge_label(&self, label: Option<String>) -> crate::Result<()> {
2297 self.window.set_badge_label(label)
2298 }
2299
2300 /// Sets the taskbar progress state.
2301 ///
2302 /// ## Platform-specific
2303 ///
2304 /// - **Linux / macOS**: Progress bar is app-wide and not specific to this window.
2305 /// - **Linux**: Only supported desktop environments with `libunity` (e.g. GNOME).
2306 /// - **iOS / Android:** Unsupported.
2307 pub fn set_progress_bar(
2308 &self,
2309 progress_state: crate::window::ProgressBarState,
2310 ) -> crate::Result<()> {
2311 self.window.set_progress_bar(progress_state)
2312 }
2313
2314 /// Sets the title bar style. **macOS only**.
2315 pub fn set_title_bar_style(&self, style: tauri_utils::TitleBarStyle) -> crate::Result<()> {
2316 self.window.set_title_bar_style(style)
2317 }
2318}
2319
2320/// Desktop window setters and actions.
2321impl<R: Runtime> WebviewWindow<R> {
2322 /// Determines if this window should be resizable.
2323 /// When resizable is set to false, native window's maximize button is automatically disabled.
2324 pub fn set_resizable(&self, resizable: bool) -> crate::Result<()> {
2325 self.window.set_resizable(resizable)
2326 }
2327
2328 /// Enable or disable the window.
2329 pub fn set_enabled(&self, enabled: bool) -> crate::Result<()> {
2330 self.webview.window().set_enabled(enabled)
2331 }
2332
2333 /// Set this window's title.
2334 pub fn set_title(&self, title: &str) -> crate::Result<()> {
2335 self.window.set_title(title)
2336 }
2337
2338 /// Show this window.
2339 pub fn show(&self) -> crate::Result<()> {
2340 self.window.show()
2341 }
2342
2343 /// Hide this window.
2344 pub fn hide(&self) -> crate::Result<()> {
2345 self.window.hide()
2346 }
2347
2348 /// Closes this window. It emits [`crate::WindowEvent::CloseRequested`] first like a user-initiated close request so you can intercept it.
2349 pub fn close(&self) -> crate::Result<()> {
2350 self.window.close()
2351 }
2352
2353 /// Destroys this window. Similar to [`Self::close`] but does not emit any events and force close the window instead.
2354 pub fn destroy(&self) -> crate::Result<()> {
2355 self.window.destroy()
2356 }
2357
2358 /// Prevents the window contents from being captured by other apps.
2359 pub fn set_content_protected(&self, protected: bool) -> crate::Result<()> {
2360 self.window.set_content_protected(protected)
2361 }
2362
2363 /// Resizes this window.
2364 pub fn set_size<S: Into<Size>>(&self, size: S) -> crate::Result<()> {
2365 self.window.set_size(size.into())
2366 }
2367
2368 /// Sets this window's minimum inner size.
2369 pub fn set_min_size<S: Into<Size>>(&self, size: Option<S>) -> crate::Result<()> {
2370 self.window.set_min_size(size.map(|s| s.into()))
2371 }
2372
2373 /// Sets this window's maximum inner size.
2374 pub fn set_max_size<S: Into<Size>>(&self, size: Option<S>) -> crate::Result<()> {
2375 self.window.set_max_size(size.map(|s| s.into()))
2376 }
2377
2378 /// Sets this window's minimum inner width.
2379 pub fn set_size_constraints(
2380 &self,
2381 constraints: tauri_runtime::window::WindowSizeConstraints,
2382 ) -> crate::Result<()> {
2383 self.window.set_size_constraints(constraints)
2384 }
2385
2386 /// Sets this window's position.
2387 pub fn set_position<Pos: Into<Position>>(&self, position: Pos) -> crate::Result<()> {
2388 self.window.set_position(position)
2389 }
2390
2391 /// Bring the window to front and focus.
2392 pub fn set_focus(&self) -> crate::Result<()> {
2393 self.window.set_focus()
2394 }
2395
2396 /// Sets whether the window can be focused.
2397 ///
2398 /// ## Platform-specific
2399 ///
2400 /// - **macOS**: If the window is already focused, it is not possible to unfocus it after calling `set_focusable(false)`.
2401 /// In this case, you might consider calling [`Window::set_focus`] but it will move the window to the back i.e. at the bottom in terms of z-order.
2402 pub fn set_focusable(&self, focusable: bool) -> crate::Result<()> {
2403 self.window.set_focusable(focusable)
2404 }
2405
2406 /// Sets the window background color.
2407 ///
2408 /// ## Platform-specific:
2409 ///
2410 /// - **iOS / Android:** Unsupported.
2411 /// - **macOS**: Not implemented for the webview layer..
2412 /// - **Windows**:
2413 /// - alpha channel is ignored for the window layer.
2414 /// - On Windows 7, transparency is not supported and the alpha value will be ignored for the webview layer..
2415 /// - On Windows 8 and newer: translucent colors are not supported so any alpha value other than `0` will be replaced by `255` for the webview layer.
2416 pub fn set_background_color(&self, color: Option<Color>) -> crate::Result<()> {
2417 self.window.set_background_color(color)?;
2418 self.webview.set_background_color(color)
2419 }
2420
2421 /// Sets the theme for this window.
2422 ///
2423 /// ## Platform-specific
2424 ///
2425 /// - **Linux / macOS**: Theme is app-wide and not specific to this window.
2426 /// - **iOS / Android:** Unsupported.
2427 pub fn set_theme(&self, theme: Option<tauri_utils::Theme>) -> crate::Result<()> {
2428 self.window.set_theme(theme)
2429 }
2430}
2431
2432/// Desktop webview APIs.
2433#[cfg(desktop)]
2434impl<R: Runtime> WebviewWindow<R> {
2435 /// Opens the dialog to prints the contents of the webview.
2436 /// Currently only supported on macOS on `wry`.
2437 /// `window.print()` works on all platforms.
2438 pub fn print(&self) -> crate::Result<()> {
2439 self.webview.print()
2440 }
2441}
2442
2443/// Webview APIs.
2444impl<R: Runtime> WebviewWindow<R> {
2445 /// Executes a closure, providing it with the webview handle that is specific to the current platform.
2446 ///
2447 /// The closure is executed on the main thread.
2448 ///
2449 /// Note that `webview2-com`, `webkit2gtk`, `objc2_web_kit` and similar crates may be updated in minor releases of Tauri.
2450 /// Therefore it's recommended to pin Tauri to at least a minor version when you're using `with_webview`.
2451 ///
2452 /// # Examples
2453 ///
2454 /// ```rust,no_run
2455 /// use tauri::Manager;
2456 ///
2457 /// fn main() {
2458 /// tauri::Builder::default()
2459 /// .setup(|app| {
2460 /// let main_webview = app.get_webview_window("main").unwrap();
2461 /// main_webview.with_webview(|webview| {
2462 /// #[cfg(target_os = "linux")]
2463 /// {
2464 /// // see <https://docs.rs/webkit2gtk/2.0.0/webkit2gtk/struct.WebView.html>
2465 /// // and <https://docs.rs/webkit2gtk/2.0.0/webkit2gtk/trait.WebViewExt.html>
2466 /// use webkit2gtk::WebViewExt;
2467 /// webview.inner().set_zoom_level(4.);
2468 /// }
2469 ///
2470 /// #[cfg(windows)]
2471 /// unsafe {
2472 /// // see <https://docs.rs/webview2-com/0.19.1/webview2_com/Microsoft/Web/WebView2/Win32/struct.ICoreWebView2Controller.html>
2473 /// webview.controller().SetZoomFactor(4.).unwrap();
2474 /// }
2475 ///
2476 /// #[cfg(target_os = "macos")]
2477 /// unsafe {
2478 /// let view: &objc2_web_kit::WKWebView = &*webview.inner().cast();
2479 /// let controller: &objc2_web_kit::WKUserContentController = &*webview.controller().cast();
2480 /// let window: &objc2_app_kit::NSWindow = &*webview.ns_window().cast();
2481 ///
2482 /// view.setPageZoom(4.);
2483 /// controller.removeAllUserScripts();
2484 /// let bg_color = objc2_app_kit::NSColor::colorWithDeviceRed_green_blue_alpha(0.5, 0.2, 0.4, 1.);
2485 /// window.setBackgroundColor(Some(&bg_color));
2486 /// }
2487 ///
2488 /// #[cfg(target_os = "android")]
2489 /// {
2490 /// use jni::objects::JValue;
2491 /// webview.jni_handle().exec(|env, _, webview| {
2492 /// env.call_method(webview, "zoomBy", "(F)V", &[JValue::Float(4.)]).unwrap();
2493 /// })
2494 /// }
2495 /// });
2496 /// Ok(())
2497 /// });
2498 /// }
2499 /// ```
2500 #[allow(clippy::needless_doctest_main)] // To avoid a large diff
2501 #[cfg(feature = "wry")]
2502 #[cfg_attr(docsrs, doc(cfg(feature = "wry")))]
2503 pub fn with_webview<F: FnOnce(crate::webview::PlatformWebview) + Send + 'static>(
2504 &self,
2505 f: F,
2506 ) -> crate::Result<()> {
2507 self.webview.with_webview(f)
2508 }
2509
2510 /// Returns the current url of the webview.
2511 pub fn url(&self) -> crate::Result<Url> {
2512 self.webview.url()
2513 }
2514
2515 /// Navigates the webview to the defined url.
2516 pub fn navigate(&self, url: Url) -> crate::Result<()> {
2517 self.webview.navigate(url)
2518 }
2519
2520 /// Reloads the current page.
2521 pub fn reload(&self) -> crate::Result<()> {
2522 self.webview.reload()
2523 }
2524
2525 /// Converts a file path to a URL that can be loaded by this webview.
2526 ///
2527 /// This is the Rust equivalent of the JavaScript `convertFileSrc` function.
2528 ///
2529 /// The `protocol-asset` Cargo feature must be enabled and the file must be included in the
2530 /// [`app.security.assetProtocol`](https://v2.tauri.app/reference/config/#assetprotocolconfig)
2531 /// scope. The protocol origin must also be allowed by the relevant
2532 /// [`app.security.csp`](https://v2.tauri.app/reference/config/#csp-1) directive,
2533 /// e.g. `img-src 'self' asset: http://asset.localhost`.
2534 ///
2535 /// On Windows and Android the URL is `http://{protocol}.localhost/{path}`
2536 /// (or `https://` if the webview was built with [`WebviewWindowBuilder::use_https_scheme`]);
2537 /// on macOS, Linux and iOS it is `{protocol}://localhost/{path}`.
2538 ///
2539 /// # Arguments
2540 ///
2541 /// * `path` - The file path to convert.
2542 /// * `protocol` - The custom protocol to use. Defaults to `asset`; you only need to set this
2543 /// when using a protocol registered with [`Builder::register_uri_scheme_protocol`](crate::Builder::register_uri_scheme_protocol).
2544 ///
2545 /// # Errors
2546 ///
2547 /// Returns [`Error::NonUtf8Path`](crate::Error::NonUtf8Path) if the path is not valid UTF-8,
2548 /// since the asset protocol could not resolve such a URL back to the file.
2549 ///
2550 /// # Examples
2551 ///
2552 /// ```rust,no_run
2553 /// use tauri::Manager;
2554 /// tauri::Builder::default()
2555 /// .setup(|app| {
2556 /// let webview = app.get_webview_window("main").unwrap();
2557 /// let video_path = app.path().app_data_dir()?.join("video.mp4");
2558 /// let url = webview.convert_file_src(&video_path, None)?;
2559 /// webview.eval(format!("document.querySelector('video').src = '{url}'"))?;
2560 /// Ok(())
2561 /// });
2562 /// ```
2563 pub fn convert_file_src<P: AsRef<Path>>(
2564 &self,
2565 path: P,
2566 protocol: Option<&str>,
2567 ) -> crate::Result<String> {
2568 self.webview.convert_file_src(path, protocol)
2569 }
2570
2571 /// Handles this window receiving an [`crate::webview::InvokeRequest`].
2572 pub fn on_message(
2573 self,
2574 request: crate::webview::InvokeRequest,
2575 responder: Box<OwnedInvokeResponder<R>>,
2576 ) {
2577 self.webview.on_message(request, responder)
2578 }
2579
2580 /// Evaluates JavaScript on this window.
2581 pub fn eval(&self, js: impl Into<String>) -> crate::Result<()> {
2582 self.webview.eval(js)
2583 }
2584
2585 /// Evaluate JavaScript with callback function on this webview.
2586 /// The evaluation result will be serialized into a JSON string and passed to the callback function.
2587 ///
2588 /// Exception is ignored because of the limitation on Windows. You can catch it yourself and return as string as a workaround.
2589 pub fn eval_with_callback(
2590 &self,
2591 js: impl Into<String>,
2592 callback: impl Fn(String) + Send + 'static,
2593 ) -> crate::Result<()> {
2594 self.webview.eval_with_callback(js, callback)
2595 }
2596
2597 /// Opens the developer tools window (Web Inspector).
2598 /// The devtools is only enabled on debug builds or with the `devtools` feature flag.
2599 ///
2600 /// ## Platform-specific
2601 ///
2602 /// - **macOS:** Only supported on macOS 10.15+.
2603 /// This is a private API on macOS, so you cannot use this if your application will be published on the App Store.
2604 ///
2605 /// # Examples
2606 ///
2607 /// ```rust,no_run
2608 /// use tauri::Manager;
2609 /// tauri::Builder::default()
2610 /// .setup(|app| {
2611 /// #[cfg(debug_assertions)]
2612 /// app.get_webview_window("main").unwrap().open_devtools();
2613 /// Ok(())
2614 /// });
2615 /// ```
2616 #[cfg(any(debug_assertions, feature = "devtools"))]
2617 #[cfg_attr(docsrs, doc(cfg(any(debug_assertions, feature = "devtools"))))]
2618 pub fn open_devtools(&self) {
2619 self.webview.open_devtools();
2620 }
2621
2622 /// Closes the developer tools window (Web Inspector).
2623 /// The devtools is only enabled on debug builds or with the `devtools` feature flag.
2624 ///
2625 /// ## Platform-specific
2626 ///
2627 /// - **macOS:** Only supported on macOS 10.15+.
2628 /// This is a private API on macOS, so you cannot use this if your application will be published on the App Store.
2629 /// - **Windows:** Unsupported.
2630 ///
2631 /// # Examples
2632 ///
2633 /// ```rust,no_run
2634 /// use tauri::Manager;
2635 /// tauri::Builder::default()
2636 /// .setup(|app| {
2637 /// #[cfg(debug_assertions)]
2638 /// {
2639 /// let webview = app.get_webview_window("main").unwrap();
2640 /// webview.open_devtools();
2641 /// std::thread::spawn(move || {
2642 /// std::thread::sleep(std::time::Duration::from_secs(10));
2643 /// webview.close_devtools();
2644 /// });
2645 /// }
2646 /// Ok(())
2647 /// });
2648 /// ```
2649 #[cfg(any(debug_assertions, feature = "devtools"))]
2650 #[cfg_attr(docsrs, doc(cfg(any(debug_assertions, feature = "devtools"))))]
2651 pub fn close_devtools(&self) {
2652 self.webview.close_devtools();
2653 }
2654
2655 /// Checks if the developer tools window (Web Inspector) is opened.
2656 /// The devtools is only enabled on debug builds or with the `devtools` feature flag.
2657 ///
2658 /// ## Platform-specific
2659 ///
2660 /// - **macOS:** Only supported on macOS 10.15+.
2661 /// This is a private API on macOS, so you cannot use this if your application will be published on the App Store.
2662 /// - **Windows:** Unsupported.
2663 ///
2664 /// # Examples
2665 ///
2666 /// ```rust,no_run
2667 /// use tauri::Manager;
2668 /// tauri::Builder::default()
2669 /// .setup(|app| {
2670 /// #[cfg(debug_assertions)]
2671 /// {
2672 /// let webview = app.get_webview_window("main").unwrap();
2673 /// if !webview.is_devtools_open() {
2674 /// webview.open_devtools();
2675 /// }
2676 /// }
2677 /// Ok(())
2678 /// });
2679 /// ```
2680 #[cfg(any(debug_assertions, feature = "devtools"))]
2681 #[cfg_attr(docsrs, doc(cfg(any(debug_assertions, feature = "devtools"))))]
2682 pub fn is_devtools_open(&self) -> bool {
2683 self.webview.is_devtools_open()
2684 }
2685
2686 /// Set the webview zoom level
2687 ///
2688 /// ## Platform-specific:
2689 ///
2690 /// - **Android**: Not supported.
2691 /// - **macOS**: available on macOS 11+ only.
2692 /// - **iOS**: available on iOS 14+ only.
2693 pub fn set_zoom(&self, scale_factor: f64) -> crate::Result<()> {
2694 self.webview.set_zoom(scale_factor)
2695 }
2696
2697 /// Clear all browsing data for this webview window.
2698 pub fn clear_all_browsing_data(&self) -> crate::Result<()> {
2699 self.webview.clear_all_browsing_data()
2700 }
2701
2702 /// Returns all cookies in the runtime's cookie store including HTTP-only and secure cookies.
2703 ///
2704 /// Note that cookies will only be returned for URLs with an http or https scheme.
2705 /// Cookies set through javascript for local files
2706 /// (such as those served from the tauri://) protocol are not currently supported.
2707 ///
2708 /// # Stability
2709 ///
2710 /// See [Self::cookies].
2711 ///
2712 /// # Known issues
2713 ///
2714 /// See [Self::cookies].
2715 pub fn cookies_for_url(&self, url: Url) -> crate::Result<Vec<Cookie<'static>>> {
2716 self.webview.cookies_for_url(url)
2717 }
2718
2719 /// Returns all cookies in the runtime's cookie store for all URLs including HTTP-only and secure cookies.
2720 ///
2721 /// Note that cookies will only be returned for URLs with an http or https scheme.
2722 /// Cookies set through javascript for local files
2723 /// (such as those served from the tauri://) protocol are not currently supported.
2724 ///
2725 /// # Stability
2726 ///
2727 /// The return value of this function leverages [`tauri_runtime::Cookie`] which re-exports the cookie crate.
2728 /// This dependency might receive updates in minor Tauri releases.
2729 ///
2730 /// # Known issues
2731 ///
2732 /// On Windows, this function deadlocks when used in a synchronous command or event handlers, see [the Webview2 issue].
2733 /// You should use `async` commands and separate threads when reading cookies.
2734 ///
2735 /// ## Platform-specific
2736 ///
2737 /// - **Android**: Unsupported, always returns an empty [`Vec`].
2738 ///
2739 /// [the Webview2 issue]: https://github.com/tauri-apps/wry/issues/583
2740 pub fn cookies(&self) -> crate::Result<Vec<Cookie<'static>>> {
2741 self.webview.cookies()
2742 }
2743
2744 /// Set a cookie for the webview.
2745 ///
2746 /// # Stability
2747 ///
2748 /// See [Self::cookies].
2749 pub fn set_cookie(&self, cookie: Cookie<'_>) -> crate::Result<()> {
2750 self.webview.set_cookie(cookie)
2751 }
2752
2753 /// Delete a cookie for the webview.
2754 ///
2755 /// # Stability
2756 ///
2757 /// See [Self::cookies].
2758 pub fn delete_cookie(&self, cookie: Cookie<'_>) -> crate::Result<()> {
2759 self.webview.delete_cookie(cookie)
2760 }
2761}
2762
2763impl<R: Runtime> Listener<R> for WebviewWindow<R> {
2764 /// Listen to an event on this webview window.
2765 ///
2766 /// # Examples
2767 ///
2768 /// ```
2769 /// use tauri::{Manager, Listener};
2770 ///
2771 /// tauri::Builder::default()
2772 /// .setup(|app| {
2773 /// let webview_window = app.get_webview_window("main").unwrap();
2774 /// webview_window.listen("component-loaded", move |event| {
2775 /// println!("window just loaded a component");
2776 /// });
2777 ///
2778 /// Ok(())
2779 /// });
2780 /// ```
2781 fn listen<F>(&self, event: impl Into<String>, handler: F) -> EventId
2782 where
2783 F: Fn(Event) + Send + 'static,
2784 {
2785 let event = EventName::new(event.into()).unwrap();
2786 self.manager().listen(
2787 event,
2788 EventTarget::WebviewWindow {
2789 label: self.label().to_string(),
2790 },
2791 handler,
2792 )
2793 }
2794
2795 /// Listen to an event on this window webview only once.
2796 ///
2797 /// See [`Self::listen`] for more information.
2798 fn once<F>(&self, event: impl Into<String>, handler: F) -> EventId
2799 where
2800 F: FnOnce(Event) + Send + 'static,
2801 {
2802 let event = EventName::new(event.into()).unwrap();
2803 self.manager().once(
2804 event,
2805 EventTarget::WebviewWindow {
2806 label: self.label().to_string(),
2807 },
2808 handler,
2809 )
2810 }
2811
2812 /// Unlisten to an event on this webview window.
2813 ///
2814 /// # Examples
2815 /// ```
2816 /// use tauri::{Manager, Listener};
2817 ///
2818 /// tauri::Builder::default()
2819 /// .setup(|app| {
2820 /// let webview_window = app.get_webview_window("main").unwrap();
2821 /// let webview_window_ = webview_window.clone();
2822 /// let handler = webview_window.listen("component-loaded", move |event| {
2823 /// println!("webview_window just loaded a component");
2824 ///
2825 /// // we no longer need to listen to the event
2826 /// // we also could have used `webview_window.once` instead
2827 /// webview_window_.unlisten(event.id());
2828 /// });
2829 ///
2830 /// // stop listening to the event when you do not need it anymore
2831 /// webview_window.unlisten(handler);
2832 ///
2833 /// Ok(())
2834 /// });
2835 /// ```
2836 fn unlisten(&self, id: EventId) {
2837 self.manager().unlisten(id)
2838 }
2839}
2840
2841impl<R: Runtime> Emitter<R> for WebviewWindow<R> {}
2842
2843impl<R: Runtime> Manager<R> for WebviewWindow<R> {
2844 fn resources_table(&self) -> MutexGuard<'_, ResourceTable> {
2845 self
2846 .webview
2847 .resources_table
2848 .lock()
2849 .expect("poisoned window resources table")
2850 }
2851}
2852
2853impl<R: Runtime> ManagerBase<R> for WebviewWindow<R> {
2854 fn manager(&self) -> &AppManager<R> {
2855 self.webview.manager()
2856 }
2857
2858 fn manager_owned(&self) -> Arc<AppManager<R>> {
2859 self.webview.manager_owned()
2860 }
2861
2862 fn runtime(&self) -> RuntimeOrDispatch<'_, R> {
2863 self.window.runtime()
2864 }
2865
2866 fn managed_app_handle(&self) -> &AppHandle<R> {
2867 self.webview.managed_app_handle()
2868 }
2869
2870 #[cfg(target_os = "android")]
2871 fn activity_name(&self) -> Option<crate::Result<String>> {
2872 Some(self.window.activity_name())
2873 }
2874
2875 #[cfg(target_os = "ios")]
2876 fn scene_identifier(&self) -> Option<crate::Result<String>> {
2877 Some(self.window.scene_identifier())
2878 }
2879}