mod.rs 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479
  1. // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. //! The Tauri webview types and functions.
  5. pub(crate) mod plugin;
  6. mod webview_window;
  7. pub use webview_window::{WebviewWindow, WebviewWindowBuilder};
  8. use http::HeaderMap;
  9. use serde::Serialize;
  10. use tauri_macros::default_runtime;
  11. pub use tauri_runtime::webview::PageLoadEvent;
  12. use tauri_runtime::{
  13. webview::{DetachedWebview, PendingWebview, WebviewAttributes},
  14. WebviewDispatch,
  15. };
  16. #[cfg(desktop)]
  17. use tauri_runtime::{
  18. window::dpi::{PhysicalPosition, PhysicalSize, Position, Size},
  19. WindowDispatch,
  20. };
  21. use tauri_utils::config::{WebviewUrl, WindowConfig};
  22. pub use url::Url;
  23. use crate::{
  24. app::UriSchemeResponder,
  25. event::{EmitArgs, EventTarget},
  26. ipc::{
  27. CallbackFn, CommandArg, CommandItem, Invoke, InvokeBody, InvokeError, InvokeMessage,
  28. InvokeResolver, Origin, OwnedInvokeResponder,
  29. },
  30. manager::{webview::WebviewLabelDef, AppManager},
  31. sealed::{ManagerBase, RuntimeOrDispatch},
  32. AppHandle, Event, EventId, EventLoopMessage, Manager, Runtime, Window,
  33. };
  34. use std::{
  35. borrow::Cow,
  36. hash::{Hash, Hasher},
  37. path::PathBuf,
  38. sync::{Arc, Mutex},
  39. };
  40. pub(crate) type WebResourceRequestHandler =
  41. dyn Fn(http::Request<Vec<u8>>, &mut http::Response<Cow<'static, [u8]>>) + Send + Sync;
  42. pub(crate) type NavigationHandler = dyn Fn(&Url) -> bool + Send;
  43. pub(crate) type UriSchemeProtocolHandler =
  44. Box<dyn Fn(http::Request<Vec<u8>>, UriSchemeResponder) + Send + Sync>;
  45. pub(crate) type OnPageLoad<R> = dyn Fn(Webview<R>, PageLoadPayload<'_>) + Send + Sync + 'static;
  46. pub(crate) type DownloadHandler<R> = dyn Fn(Webview<R>, DownloadEvent<'_>) -> bool + Send + Sync;
  47. #[derive(Clone, Serialize)]
  48. struct CreatedEvent {
  49. label: String,
  50. }
  51. /// Download event for the [`WebviewBuilder#method.on_download`] hook.
  52. #[non_exhaustive]
  53. pub enum DownloadEvent<'a> {
  54. /// Download requested.
  55. Requested {
  56. /// The url being downloaded.
  57. url: Url,
  58. /// Represents where the file will be downloaded to.
  59. /// Can be used to set the download location by assigning a new path to it.
  60. /// The assigned path _must_ be absolute.
  61. destination: &'a mut PathBuf,
  62. },
  63. /// Download finished.
  64. Finished {
  65. /// The URL of the original download request.
  66. url: Url,
  67. /// Potentially representing the filesystem path the file was downloaded to.
  68. ///
  69. /// A value of `None` being passed instead of a `PathBuf` does not necessarily indicate that the download
  70. /// did not succeed, and may instead indicate some other failure - always check the third parameter if you need to
  71. /// know if the download succeeded.
  72. ///
  73. /// ## Platform-specific:
  74. ///
  75. /// - **macOS**: The second parameter indicating the path the file was saved to is always empty, due to API
  76. /// limitations.
  77. path: Option<PathBuf>,
  78. /// Indicates if the download succeeded or not.
  79. success: bool,
  80. },
  81. }
  82. /// The payload for the [`WebviewBuilder::on_page_load`] hook.
  83. #[derive(Debug, Clone)]
  84. pub struct PageLoadPayload<'a> {
  85. pub(crate) url: &'a Url,
  86. pub(crate) event: PageLoadEvent,
  87. }
  88. impl<'a> PageLoadPayload<'a> {
  89. /// The page URL.
  90. pub fn url(&self) -> &'a Url {
  91. self.url
  92. }
  93. /// The page load event.
  94. pub fn event(&self) -> PageLoadEvent {
  95. self.event
  96. }
  97. }
  98. /// The IPC invoke request.
  99. #[derive(Debug)]
  100. pub struct InvokeRequest {
  101. /// The invoke command.
  102. pub cmd: String,
  103. /// The success callback.
  104. pub callback: CallbackFn,
  105. /// The error callback.
  106. pub error: CallbackFn,
  107. /// The body of the request.
  108. pub body: InvokeBody,
  109. /// The request headers.
  110. pub headers: HeaderMap,
  111. }
  112. /// The platform webview handle. Accessed with [`Webview#method.with_webview`];
  113. #[cfg(feature = "wry")]
  114. #[cfg_attr(docsrs, doc(cfg(feature = "wry")))]
  115. pub struct PlatformWebview(tauri_runtime_wry::Webview);
  116. #[cfg(feature = "wry")]
  117. impl PlatformWebview {
  118. /// Returns [`webkit2gtk::WebView`] handle.
  119. #[cfg(any(
  120. target_os = "linux",
  121. target_os = "dragonfly",
  122. target_os = "freebsd",
  123. target_os = "netbsd",
  124. target_os = "openbsd"
  125. ))]
  126. #[cfg_attr(
  127. docsrs,
  128. doc(cfg(any(
  129. target_os = "linux",
  130. target_os = "dragonfly",
  131. target_os = "freebsd",
  132. target_os = "netbsd",
  133. target_os = "openbsd"
  134. )))
  135. )]
  136. pub fn inner(&self) -> webkit2gtk::WebView {
  137. self.0.clone()
  138. }
  139. /// Returns the WebView2 controller.
  140. #[cfg(windows)]
  141. #[cfg_attr(docsrs, doc(cfg(windows)))]
  142. pub fn controller(
  143. &self,
  144. ) -> webview2_com::Microsoft::Web::WebView2::Win32::ICoreWebView2Controller {
  145. self.0.controller.clone()
  146. }
  147. /// Returns the [WKWebView] handle.
  148. ///
  149. /// [WKWebView]: https://developer.apple.com/documentation/webkit/wkwebview
  150. #[cfg(any(target_os = "macos", target_os = "ios"))]
  151. #[cfg_attr(docsrs, doc(cfg(any(target_os = "macos", target_os = "ios"))))]
  152. pub fn inner(&self) -> cocoa::base::id {
  153. self.0.webview
  154. }
  155. /// Returns WKWebView [controller] handle.
  156. ///
  157. /// [controller]: https://developer.apple.com/documentation/webkit/wkusercontentcontroller
  158. #[cfg(any(target_os = "macos", target_os = "ios"))]
  159. #[cfg_attr(docsrs, doc(cfg(any(target_os = "macos", target_os = "ios"))))]
  160. pub fn controller(&self) -> cocoa::base::id {
  161. self.0.manager
  162. }
  163. /// Returns [NSWindow] associated with the WKWebView webview.
  164. ///
  165. /// [NSWindow]: https://developer.apple.com/documentation/appkit/nswindow
  166. #[cfg(target_os = "macos")]
  167. #[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
  168. pub fn ns_window(&self) -> cocoa::base::id {
  169. self.0.ns_window
  170. }
  171. /// Returns [UIViewController] used by the WKWebView webview NSWindow.
  172. ///
  173. /// [UIViewController]: https://developer.apple.com/documentation/uikit/uiviewcontroller
  174. #[cfg(target_os = "ios")]
  175. #[cfg_attr(docsrs, doc(cfg(target_os = "ios")))]
  176. pub fn view_controller(&self) -> cocoa::base::id {
  177. self.0.view_controller
  178. }
  179. /// Returns handle for JNI execution.
  180. #[cfg(target_os = "android")]
  181. pub fn jni_handle(&self) -> tauri_runtime_wry::wry::JniHandle {
  182. self.0
  183. }
  184. }
  185. macro_rules! unstable_struct {
  186. (#[doc = $doc:expr] $($tokens:tt)*) => {
  187. #[cfg(any(test, feature = "unstable"))]
  188. #[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
  189. #[doc = $doc]
  190. pub $($tokens)*
  191. #[cfg(not(any(test, feature = "unstable")))]
  192. pub(crate) $($tokens)*
  193. }
  194. }
  195. unstable_struct!(
  196. #[doc = "A builder for a webview."]
  197. struct WebviewBuilder<R: Runtime> {
  198. pub(crate) label: String,
  199. pub(crate) webview_attributes: WebviewAttributes,
  200. pub(crate) web_resource_request_handler: Option<Box<WebResourceRequestHandler>>,
  201. pub(crate) navigation_handler: Option<Box<NavigationHandler>>,
  202. pub(crate) on_page_load_handler: Option<Box<OnPageLoad<R>>>,
  203. pub(crate) download_handler: Option<Arc<DownloadHandler<R>>>,
  204. }
  205. );
  206. #[cfg_attr(not(feature = "unstable"), allow(dead_code))]
  207. impl<R: Runtime> WebviewBuilder<R> {
  208. /// Initializes a webview builder with the given webview label and URL to load.
  209. ///
  210. /// # Known issues
  211. ///
  212. /// On Windows, this function deadlocks when used in a synchronous command, see [the Webview2 issue].
  213. /// You should use `async` commands when creating windows.
  214. ///
  215. /// # Examples
  216. ///
  217. /// - Create a webview in the setup hook:
  218. ///
  219. #[cfg_attr(
  220. feature = "unstable",
  221. doc = r####"
  222. ```
  223. tauri::Builder::default()
  224. .setup(|app| {
  225. let window = tauri::window::WindowBuilder::new(app, "label").build()?;
  226. let webview_builder = tauri::webview::WebviewBuilder::new("label", tauri::WebviewUrl::App("index.html".into()));
  227. let webview = window.add_child(webview_builder, tauri::LogicalPosition::new(0, 0), window.inner_size().unwrap());
  228. Ok(())
  229. });
  230. ```
  231. "####
  232. )]
  233. ///
  234. /// - Create a webview in a separate thread:
  235. ///
  236. #[cfg_attr(
  237. feature = "unstable",
  238. doc = r####"
  239. ```
  240. tauri::Builder::default()
  241. .setup(|app| {
  242. let handle = app.handle().clone();
  243. std::thread::spawn(move || {
  244. let window = tauri::window::WindowBuilder::new(&handle, "label").build().unwrap();
  245. let webview_builder = tauri::webview::WebviewBuilder::new("label", tauri::WebviewUrl::App("index.html".into()));
  246. window.add_child(webview_builder, tauri::LogicalPosition::new(0, 0), window.inner_size().unwrap());
  247. });
  248. Ok(())
  249. });
  250. ```
  251. "####
  252. )]
  253. ///
  254. /// - Create a webview in a command:
  255. ///
  256. #[cfg_attr(
  257. feature = "unstable",
  258. doc = r####"
  259. ```
  260. #[tauri::command]
  261. async fn create_window(app: tauri::AppHandle) {
  262. let window = tauri::window::WindowBuilder::new(&app, "label").build().unwrap();
  263. let webview_builder = tauri::webview::WebviewBuilder::new("label", tauri::WebviewUrl::External("https://tauri.app/".parse().unwrap()));
  264. window.add_child(webview_builder, tauri::LogicalPosition::new(0, 0), window.inner_size().unwrap());
  265. }
  266. ```
  267. "####
  268. )]
  269. ///
  270. /// [the Webview2 issue]: https://github.com/tauri-apps/wry/issues/583
  271. pub fn new<L: Into<String>>(label: L, url: WebviewUrl) -> Self {
  272. Self {
  273. label: label.into(),
  274. webview_attributes: WebviewAttributes::new(url),
  275. web_resource_request_handler: None,
  276. navigation_handler: None,
  277. on_page_load_handler: None,
  278. download_handler: None,
  279. }
  280. }
  281. /// Initializes a webview builder from a [`WindowConfig`] from tauri.conf.json.
  282. /// Keep in mind that you can't create 2 webviews with the same `label` so make sure
  283. /// that the initial webview was closed or change the label of the new [`WebviewBuilder`].
  284. ///
  285. /// # Known issues
  286. ///
  287. /// On Windows, this function deadlocks when used in a synchronous command, see [the Webview2 issue].
  288. /// You should use `async` commands when creating webviews.
  289. ///
  290. /// # Examples
  291. ///
  292. /// - Create a webview in a command:
  293. ///
  294. #[cfg_attr(
  295. feature = "unstable",
  296. doc = r####"
  297. ```
  298. #[tauri::command]
  299. async fn reopen_window(app: tauri::AppHandle) {
  300. let window = tauri::window::WindowBuilder::from_config(&app, &app.config().tauri.windows.get(0).unwrap().clone())
  301. .unwrap()
  302. .build()
  303. .unwrap();
  304. }
  305. ```
  306. "####
  307. )]
  308. ///
  309. /// [the Webview2 issue]: https://github.com/tauri-apps/wry/issues/583
  310. pub fn from_config(config: &WindowConfig) -> Self {
  311. Self {
  312. label: config.label.clone(),
  313. webview_attributes: WebviewAttributes::from(config),
  314. web_resource_request_handler: None,
  315. navigation_handler: None,
  316. on_page_load_handler: None,
  317. download_handler: None,
  318. }
  319. }
  320. /// Defines a closure to be executed when the webview makes an HTTP request for a web resource, allowing you to modify the response.
  321. ///
  322. /// Currently only implemented for the `tauri` URI protocol.
  323. ///
  324. /// **NOTE:** Currently this is **not** executed when using external URLs such as a development server,
  325. /// but it might be implemented in the future. **Always** check the request URL.
  326. ///
  327. /// # Examples
  328. ///
  329. #[cfg_attr(
  330. feature = "unstable",
  331. doc = r####"
  332. ```rust,no_run
  333. use tauri::{
  334. utils::config::{Csp, CspDirectiveSources, WebviewUrl},
  335. window::WindowBuilder,
  336. webview::WebviewBuilder,
  337. };
  338. use http::header::HeaderValue;
  339. use std::collections::HashMap;
  340. tauri::Builder::default()
  341. .setup(|app| {
  342. let window = tauri::window::WindowBuilder::new(app, "label").build()?;
  343. let webview_builder = WebviewBuilder::new("core", WebviewUrl::App("index.html".into()))
  344. .on_web_resource_request(|request, response| {
  345. if request.uri().scheme_str() == Some("tauri") {
  346. // if we have a CSP header, Tauri is loading an HTML file
  347. // for this example, let's dynamically change the CSP
  348. if let Some(csp) = response.headers_mut().get_mut("Content-Security-Policy") {
  349. // use the tauri helper to parse the CSP policy to a map
  350. let mut csp_map: HashMap<String, CspDirectiveSources> = Csp::Policy(csp.to_str().unwrap().to_string()).into();
  351. csp_map.entry("script-src".to_string()).or_insert_with(Default::default).push("'unsafe-inline'");
  352. // use the tauri helper to get a CSP string from the map
  353. let csp_string = Csp::from(csp_map).to_string();
  354. *csp = HeaderValue::from_str(&csp_string).unwrap();
  355. }
  356. }
  357. });
  358. let webview = window.add_child(webview_builder, tauri::LogicalPosition::new(0, 0), window.inner_size().unwrap())?;
  359. Ok(())
  360. });
  361. ```
  362. "####
  363. )]
  364. pub fn on_web_resource_request<
  365. F: Fn(http::Request<Vec<u8>>, &mut http::Response<Cow<'static, [u8]>>) + Send + Sync + 'static,
  366. >(
  367. mut self,
  368. f: F,
  369. ) -> Self {
  370. self.web_resource_request_handler.replace(Box::new(f));
  371. self
  372. }
  373. /// Defines a closure to be executed when the webview navigates to a URL. Returning `false` cancels the navigation.
  374. ///
  375. /// # Examples
  376. ///
  377. #[cfg_attr(
  378. feature = "unstable",
  379. doc = r####"
  380. ```rust,no_run
  381. use tauri::{
  382. utils::config::{Csp, CspDirectiveSources, WebviewUrl},
  383. window::WindowBuilder,
  384. webview::WebviewBuilder,
  385. };
  386. use http::header::HeaderValue;
  387. use std::collections::HashMap;
  388. tauri::Builder::default()
  389. .setup(|app| {
  390. let window = tauri::window::WindowBuilder::new(app, "label").build()?;
  391. let webview_builder = WebviewBuilder::new("core", WebviewUrl::App("index.html".into()))
  392. .on_navigation(|url| {
  393. // allow the production URL or localhost on dev
  394. url.scheme() == "tauri" || (cfg!(dev) && url.host_str() == Some("localhost"))
  395. });
  396. let webview = window.add_child(webview_builder, tauri::LogicalPosition::new(0, 0), window.inner_size().unwrap())?;
  397. Ok(())
  398. });
  399. ```
  400. "####
  401. )]
  402. pub fn on_navigation<F: Fn(&Url) -> bool + Send + 'static>(mut self, f: F) -> Self {
  403. self.navigation_handler.replace(Box::new(f));
  404. self
  405. }
  406. /// Set a download event handler to be notified when a download is requested or finished.
  407. ///
  408. /// Returning `false` prevents the download from happening on a [`DownloadEvent::Requested`] event.
  409. ///
  410. /// # Examples
  411. ///
  412. #[cfg_attr(
  413. feature = "unstable",
  414. doc = r####"
  415. ```rust,no_run
  416. use tauri::{
  417. utils::config::{Csp, CspDirectiveSources, WebviewUrl},
  418. window::WindowBuilder,
  419. webview::{DownloadEvent, WebviewBuilder},
  420. };
  421. tauri::Builder::default()
  422. .setup(|app| {
  423. let window = WindowBuilder::new(app, "label").build()?;
  424. let webview_builder = WebviewBuilder::new("core", WebviewUrl::App("index.html".into()))
  425. .on_download(|webview, event| {
  426. match event {
  427. DownloadEvent::Requested { url, destination } => {
  428. println!("downloading {}", url);
  429. *destination = "/home/tauri/target/path".into();
  430. }
  431. DownloadEvent::Finished { url, path, success } => {
  432. println!("downloaded {} to {:?}, success: {}", url, path, success);
  433. }
  434. _ => (),
  435. }
  436. // let the download start
  437. true
  438. });
  439. let webview = window.add_child(webview_builder, tauri::LogicalPosition::new(0, 0), window.inner_size().unwrap())?;
  440. Ok(())
  441. });
  442. ```
  443. "####
  444. )]
  445. pub fn on_download<F: Fn(Webview<R>, DownloadEvent<'_>) -> bool + Send + Sync + 'static>(
  446. mut self,
  447. f: F,
  448. ) -> Self {
  449. self.download_handler.replace(Arc::new(f));
  450. self
  451. }
  452. /// Defines a closure to be executed when a page load event is triggered.
  453. /// The event can be either [`PageLoadEvent::Started`] if the page has started loading
  454. /// or [`PageLoadEvent::Finished`] when the page finishes loading.
  455. ///
  456. /// # Examples
  457. ///
  458. #[cfg_attr(
  459. feature = "unstable",
  460. doc = r####"
  461. ```rust,no_run
  462. use tauri::{
  463. utils::config::{Csp, CspDirectiveSources, WebviewUrl},
  464. window::WindowBuilder,
  465. webview::{PageLoadEvent, WebviewBuilder},
  466. };
  467. use http::header::HeaderValue;
  468. use std::collections::HashMap;
  469. tauri::Builder::default()
  470. .setup(|app| {
  471. let window = tauri::window::WindowBuilder::new(app, "label").build()?;
  472. let webview_builder = WebviewBuilder::new("core", WebviewUrl::App("index.html".into()))
  473. .on_page_load(|webview, payload| {
  474. match payload.event() {
  475. PageLoadEvent::Started => {
  476. println!("{} finished loading", payload.url());
  477. }
  478. PageLoadEvent::Finished => {
  479. println!("{} finished loading", payload.url());
  480. }
  481. }
  482. });
  483. let webview = window.add_child(webview_builder, tauri::LogicalPosition::new(0, 0), window.inner_size().unwrap())?;
  484. Ok(())
  485. });
  486. ```
  487. "####
  488. )]
  489. pub fn on_page_load<F: Fn(Webview<R>, PageLoadPayload<'_>) + Send + Sync + 'static>(
  490. mut self,
  491. f: F,
  492. ) -> Self {
  493. self.on_page_load_handler.replace(Box::new(f));
  494. self
  495. }
  496. pub(crate) fn into_pending_webview<M: Manager<R>>(
  497. mut self,
  498. manager: &M,
  499. window_label: &str,
  500. window_labels: &[String],
  501. webview_labels: &[WebviewLabelDef],
  502. ) -> crate::Result<PendingWebview<EventLoopMessage, R>> {
  503. let mut pending = PendingWebview::new(self.webview_attributes, self.label.clone())?;
  504. pending.navigation_handler = self.navigation_handler.take();
  505. pending.web_resource_request_handler = self.web_resource_request_handler.take();
  506. if let Some(download_handler) = self.download_handler.take() {
  507. let label = pending.label.clone();
  508. let manager = manager.manager_owned();
  509. pending.download_handler.replace(Arc::new(move |event| {
  510. if let Some(w) = manager.get_webview(&label) {
  511. download_handler(
  512. w,
  513. match event {
  514. tauri_runtime::webview::DownloadEvent::Requested { url, destination } => {
  515. DownloadEvent::Requested { url, destination }
  516. }
  517. tauri_runtime::webview::DownloadEvent::Finished { url, path, success } => {
  518. DownloadEvent::Finished { url, path, success }
  519. }
  520. },
  521. )
  522. } else {
  523. false
  524. }
  525. }));
  526. }
  527. if let Some(on_page_load_handler) = self.on_page_load_handler.take() {
  528. let label = pending.label.clone();
  529. let manager = manager.manager_owned();
  530. pending
  531. .on_page_load_handler
  532. .replace(Box::new(move |url, event| {
  533. if let Some(w) = manager.get_webview(&label) {
  534. on_page_load_handler(w, PageLoadPayload { url: &url, event });
  535. }
  536. }));
  537. }
  538. manager.manager().webview.prepare_webview(
  539. manager,
  540. pending,
  541. window_label,
  542. window_labels,
  543. webview_labels,
  544. )
  545. }
  546. /// Creates a new webview on the given window.
  547. #[cfg(desktop)]
  548. pub(crate) fn build(
  549. self,
  550. window: Window<R>,
  551. position: Position,
  552. size: Size,
  553. ) -> crate::Result<Webview<R>> {
  554. let window_labels = window
  555. .manager()
  556. .window
  557. .labels()
  558. .into_iter()
  559. .collect::<Vec<_>>();
  560. let webview_labels = window
  561. .manager()
  562. .webview
  563. .webviews_lock()
  564. .values()
  565. .map(|w| WebviewLabelDef {
  566. window_label: w.window.label().to_string(),
  567. label: w.label().to_string(),
  568. })
  569. .collect::<Vec<_>>();
  570. let app_manager = window.manager();
  571. let mut pending =
  572. self.into_pending_webview(&window, window.label(), &window_labels, &webview_labels)?;
  573. pending.webview_attributes.bounds = Some((position, size));
  574. let webview = match &mut window.runtime() {
  575. RuntimeOrDispatch::Dispatch(dispatcher) => dispatcher.create_webview(pending),
  576. _ => unimplemented!(),
  577. }
  578. .map(|webview| app_manager.webview.attach_webview(window.clone(), webview))?;
  579. app_manager.webview.eval_script_all(format!(
  580. "window.__TAURI_INTERNALS__.metadata.windows = {window_labels_array}.map(function (label) {{ return {{ label: label }} }})",
  581. window_labels_array = serde_json::to_string(&app_manager.webview.labels())?,
  582. ))?;
  583. app_manager.emit_filter(
  584. "tauri://webview-created",
  585. Some(CreatedEvent {
  586. label: webview.label().into(),
  587. }),
  588. |s| match s {
  589. EventTarget::Webview { label } => label == webview.label(),
  590. _ => false,
  591. },
  592. )?;
  593. Ok(webview)
  594. }
  595. }
  596. /// Webview attributes.
  597. impl<R: Runtime> WebviewBuilder<R> {
  598. /// Sets whether clicking an inactive window also clicks through to the webview.
  599. #[must_use]
  600. pub fn accept_first_mouse(mut self, accept: bool) -> Self {
  601. self.webview_attributes.accept_first_mouse = accept;
  602. self
  603. }
  604. /// Adds the provided JavaScript to a list of scripts that should be run after the global object has been created,
  605. /// but before the HTML document has been parsed and before any other script included by the HTML document is run.
  606. ///
  607. /// Since it runs on all top-level document and child frame page navigations,
  608. /// it's recommended to check the `window.location` to guard your script from running on unexpected origins.
  609. ///
  610. /// # Examples
  611. ///
  612. #[cfg_attr(
  613. feature = "unstable",
  614. doc = r####"
  615. ```rust
  616. use tauri::{WindowBuilder, Runtime};
  617. const INIT_SCRIPT: &str = r#"
  618. if (window.location.origin === 'https://tauri.app') {
  619. console.log("hello world from js init script");
  620. window.__MY_CUSTOM_PROPERTY__ = { foo: 'bar' };
  621. }
  622. "#;
  623. fn main() {
  624. tauri::Builder::default()
  625. .setup(|app| {
  626. let window = tauri::window::WindowBuilder::new(app, "label").build()?;
  627. let webview_builder = tauri::webview::WebviewBuilder::new("label", tauri::WebviewUrl::App("index.html".into()))
  628. .initialization_script(INIT_SCRIPT);
  629. let webview = window.add_child(webview_builder, tauri::LogicalPosition::new(0, 0), window.inner_size().unwrap())?;
  630. Ok(())
  631. });
  632. }
  633. ```
  634. "####
  635. )]
  636. #[must_use]
  637. pub fn initialization_script(mut self, script: &str) -> Self {
  638. self
  639. .webview_attributes
  640. .initialization_scripts
  641. .push(script.to_string());
  642. self
  643. }
  644. /// Set the user agent for the webview
  645. #[must_use]
  646. pub fn user_agent(mut self, user_agent: &str) -> Self {
  647. self.webview_attributes.user_agent = Some(user_agent.to_string());
  648. self
  649. }
  650. /// Set additional arguments for the webview.
  651. ///
  652. /// ## Platform-specific
  653. ///
  654. /// - **macOS / Linux / Android / iOS**: Unsupported.
  655. ///
  656. /// ## Warning
  657. ///
  658. /// By default wry passes `--disable-features=msWebOOUI,msPdfOOUI,msSmartScreenProtection`
  659. /// so if you use this method, you also need to disable these components by yourself if you want.
  660. #[must_use]
  661. pub fn additional_browser_args(mut self, additional_args: &str) -> Self {
  662. self.webview_attributes.additional_browser_args = Some(additional_args.to_string());
  663. self
  664. }
  665. /// Data directory for the webview.
  666. #[must_use]
  667. pub fn data_directory(mut self, data_directory: PathBuf) -> Self {
  668. self
  669. .webview_attributes
  670. .data_directory
  671. .replace(data_directory);
  672. self
  673. }
  674. /// Disables the file drop handler. This is required to use drag and drop APIs on the front end on Windows.
  675. #[must_use]
  676. pub fn disable_file_drop_handler(mut self) -> Self {
  677. self.webview_attributes.file_drop_handler_enabled = false;
  678. self
  679. }
  680. /// Enables clipboard access for the page rendered on **Linux** and **Windows**.
  681. ///
  682. /// **macOS** doesn't provide such method and is always enabled by default,
  683. /// but you still need to add menu item accelerators to use shortcuts.
  684. #[must_use]
  685. pub fn enable_clipboard_access(mut self) -> Self {
  686. self.webview_attributes.clipboard = true;
  687. self
  688. }
  689. /// Enable or disable incognito mode for the WebView..
  690. ///
  691. /// ## Platform-specific:
  692. ///
  693. /// **Android**: Unsupported.
  694. #[must_use]
  695. pub fn incognito(mut self, incognito: bool) -> Self {
  696. self.webview_attributes.incognito = incognito;
  697. self
  698. }
  699. /// Enable or disable transparency for the WebView.
  700. #[cfg(any(not(target_os = "macos"), feature = "macos-private-api"))]
  701. #[cfg_attr(
  702. docsrs,
  703. doc(cfg(any(not(target_os = "macos"), feature = "macos-private-api")))
  704. )]
  705. #[must_use]
  706. pub fn transparent(mut self, transparent: bool) -> Self {
  707. self.webview_attributes.transparent = transparent;
  708. self
  709. }
  710. /// Sets the webview to automatically grow and shrink its size and position when the parent window resizes.
  711. #[must_use]
  712. pub fn auto_resize(mut self) -> Self {
  713. self.webview_attributes.auto_resize = true;
  714. self
  715. }
  716. }
  717. /// Webview.
  718. #[default_runtime(crate::Wry, wry)]
  719. pub struct Webview<R: Runtime> {
  720. pub(crate) window: Window<R>,
  721. /// The webview created by the runtime.
  722. pub(crate) webview: DetachedWebview<EventLoopMessage, R>,
  723. }
  724. impl<R: Runtime> std::fmt::Debug for Webview<R> {
  725. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  726. f.debug_struct("Window")
  727. .field("window", &self.window)
  728. .field("webview", &self.webview)
  729. .finish()
  730. }
  731. }
  732. impl<R: Runtime> Clone for Webview<R> {
  733. fn clone(&self) -> Self {
  734. Self {
  735. window: self.window.clone(),
  736. webview: self.webview.clone(),
  737. }
  738. }
  739. }
  740. impl<R: Runtime> Hash for Webview<R> {
  741. /// Only use the [`Webview`]'s label to represent its hash.
  742. fn hash<H: Hasher>(&self, state: &mut H) {
  743. self.webview.label.hash(state)
  744. }
  745. }
  746. impl<R: Runtime> Eq for Webview<R> {}
  747. impl<R: Runtime> PartialEq for Webview<R> {
  748. /// Only use the [`Webview`]'s label to compare equality.
  749. fn eq(&self, other: &Self) -> bool {
  750. self.webview.label.eq(&other.webview.label)
  751. }
  752. }
  753. /// Base webview functions.
  754. impl<R: Runtime> Webview<R> {
  755. /// Create a new webview that is attached to the window.
  756. pub(crate) fn new(window: Window<R>, webview: DetachedWebview<EventLoopMessage, R>) -> Self {
  757. Self { window, webview }
  758. }
  759. /// Initializes a webview builder with the given window label and URL to load on the webview.
  760. ///
  761. /// Data URLs are only supported with the `webview-data-url` feature flag.
  762. #[cfg(feature = "unstable")]
  763. #[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
  764. pub fn builder<L: Into<String>>(label: L, url: WebviewUrl) -> WebviewBuilder<R> {
  765. WebviewBuilder::new(label.into(), url)
  766. }
  767. /// Runs the given closure on the main thread.
  768. pub fn run_on_main_thread<F: FnOnce() + Send + 'static>(&self, f: F) -> crate::Result<()> {
  769. self
  770. .webview
  771. .dispatcher
  772. .run_on_main_thread(f)
  773. .map_err(Into::into)
  774. }
  775. /// The webview label.
  776. pub fn label(&self) -> &str {
  777. &self.webview.label
  778. }
  779. }
  780. /// Desktop webview setters and actions.
  781. #[cfg(desktop)]
  782. impl<R: Runtime> Webview<R> {
  783. /// Opens the dialog to prints the contents of the webview.
  784. /// Currently only supported on macOS on `wry`.
  785. /// `window.print()` works on all platforms.
  786. pub fn print(&self) -> crate::Result<()> {
  787. self.webview.dispatcher.print().map_err(Into::into)
  788. }
  789. /// Closes this webview.
  790. pub fn close(&self) -> crate::Result<()> {
  791. if self.window.webview_window {
  792. self.window.close()
  793. } else {
  794. self.webview.dispatcher.close().map_err(Into::into)
  795. }
  796. }
  797. /// Resizes this webview.
  798. pub fn set_size<S: Into<Size>>(&self, size: S) -> crate::Result<()> {
  799. if self.window.webview_window {
  800. self.window.set_size(size.into())
  801. } else {
  802. self
  803. .webview
  804. .dispatcher
  805. .set_size(size.into())
  806. .map_err(Into::into)
  807. }
  808. }
  809. /// Sets this webviews's position.
  810. pub fn set_position<Pos: Into<Position>>(&self, position: Pos) -> crate::Result<()> {
  811. if self.window.webview_window {
  812. self.window.set_position(position.into())
  813. } else {
  814. self
  815. .webview
  816. .dispatcher
  817. .set_position(position.into())
  818. .map_err(Into::into)
  819. }
  820. }
  821. /// Focus the webview.
  822. pub fn set_focus(&self) -> crate::Result<()> {
  823. self.webview.dispatcher.set_focus().map_err(Into::into)
  824. }
  825. /// Returns the webview position.
  826. ///
  827. /// - For child webviews, returns the position of the top-left hand corner of the webviews's client area relative to the top-left hand corner of the parent window.
  828. /// - For webview window, returns the inner position of the window.
  829. pub fn position(&self) -> crate::Result<PhysicalPosition<i32>> {
  830. if self.window.webview_window {
  831. self.window.inner_position()
  832. } else {
  833. self.webview.dispatcher.position().map_err(Into::into)
  834. }
  835. }
  836. /// Returns the physical size of the webviews's client area.
  837. pub fn size(&self) -> crate::Result<PhysicalSize<u32>> {
  838. if self.window.webview_window {
  839. self.window.inner_size()
  840. } else {
  841. self.webview.dispatcher.size().map_err(Into::into)
  842. }
  843. }
  844. }
  845. /// Webview APIs.
  846. impl<R: Runtime> Webview<R> {
  847. /// The window that is hosting this webview.
  848. pub fn window(&self) -> &Window<R> {
  849. &self.window
  850. }
  851. /// Executes a closure, providing it with the webview handle that is specific to the current platform.
  852. ///
  853. /// The closure is executed on the main thread.
  854. ///
  855. /// # Examples
  856. ///
  857. #[cfg_attr(
  858. feature = "unstable",
  859. doc = r####"
  860. ```rust,no_run
  861. #[cfg(target_os = "macos")]
  862. #[macro_use]
  863. extern crate objc;
  864. use tauri::Manager;
  865. fn main() {
  866. tauri::Builder::default()
  867. .setup(|app| {
  868. let main_webview = app.get_webview("main").unwrap();
  869. main_webview.with_webview(|webview| {
  870. #[cfg(target_os = "linux")]
  871. {
  872. // see https://docs.rs/webkit2gtk/2.0.0/webkit2gtk/struct.WebView.html
  873. // and https://docs.rs/webkit2gtk/2.0.0/webkit2gtk/trait.WebViewExt.html
  874. use webkit2gtk::WebViewExt;
  875. webview.inner().set_zoom_level(4.);
  876. }
  877. #[cfg(windows)]
  878. unsafe {
  879. // see https://docs.rs/webview2-com/0.19.1/webview2_com/Microsoft/Web/WebView2/Win32/struct.ICoreWebView2Controller.html
  880. webview.controller().SetZoomFactor(4.).unwrap();
  881. }
  882. #[cfg(target_os = "macos")]
  883. unsafe {
  884. let () = msg_send![webview.inner(), setPageZoom: 4.];
  885. let () = msg_send![webview.controller(), removeAllUserScripts];
  886. let bg_color: cocoa::base::id = msg_send![class!(NSColor), colorWithDeviceRed:0.5 green:0.2 blue:0.4 alpha:1.];
  887. let () = msg_send![webview.ns_window(), setBackgroundColor: bg_color];
  888. }
  889. #[cfg(target_os = "android")]
  890. {
  891. use jni::objects::JValue;
  892. webview.jni_handle().exec(|env, _, webview| {
  893. env.call_method(webview, "zoomBy", "(F)V", &[JValue::Float(4.)]).unwrap();
  894. })
  895. }
  896. });
  897. Ok(())
  898. });
  899. }
  900. ```
  901. "####
  902. )]
  903. #[cfg(feature = "wry")]
  904. #[cfg_attr(docsrs, doc(feature = "wry"))]
  905. pub fn with_webview<F: FnOnce(PlatformWebview) + Send + 'static>(
  906. &self,
  907. f: F,
  908. ) -> crate::Result<()> {
  909. self
  910. .webview
  911. .dispatcher
  912. .with_webview(|w| f(PlatformWebview(*w.downcast().unwrap())))
  913. .map_err(Into::into)
  914. }
  915. /// Returns the current url of the webview.
  916. // TODO: in v2, change this type to Result
  917. pub fn url(&self) -> Url {
  918. self.webview.dispatcher.url().unwrap()
  919. }
  920. /// Navigates the webview to the defined url.
  921. pub fn navigate(&mut self, url: Url) {
  922. self.webview.dispatcher.navigate(url).unwrap();
  923. }
  924. fn is_local_url(&self, current_url: &Url) -> bool {
  925. // if from `tauri://` custom protocol
  926. ({
  927. let protocol_url = self.manager().protocol_url();
  928. current_url.scheme() == protocol_url.scheme()
  929. && current_url.domain() == protocol_url.domain()
  930. }) ||
  931. // or if relative to `distDir` or `devPath`
  932. self
  933. .manager()
  934. .get_url()
  935. .make_relative(current_url)
  936. .is_some()
  937. // or from a custom protocol registered by the user
  938. || ({
  939. let scheme = current_url.scheme();
  940. let protocols = self.manager().webview.uri_scheme_protocols.lock().unwrap();
  941. #[cfg(all(not(windows), not(target_os = "android")))]
  942. let local = protocols.contains_key(scheme);
  943. // on window and android, custom protocols are `http://<protocol-name>.path/to/route`
  944. // so we check using the first part of the domain
  945. #[cfg(any(windows, target_os = "android"))]
  946. let local = {
  947. let protocol_url = self.manager().protocol_url();
  948. let maybe_protocol = current_url
  949. .domain()
  950. .and_then(|d| d .split_once('.'))
  951. .unwrap_or_default()
  952. .0;
  953. protocols.contains_key(maybe_protocol) && scheme == protocol_url.scheme()
  954. };
  955. local
  956. })
  957. }
  958. /// Handles this window receiving an [`InvokeRequest`].
  959. pub fn on_message(self, request: InvokeRequest, responder: Box<OwnedInvokeResponder<R>>) {
  960. let manager = self.manager_owned();
  961. let current_url = self.url();
  962. let is_local = self.is_local_url(&current_url);
  963. let custom_responder = self.manager().webview.invoke_responder.clone();
  964. let resolver = InvokeResolver::new(
  965. self.clone(),
  966. Arc::new(Mutex::new(Some(Box::new(
  967. #[allow(unused_variables)]
  968. move |webview: Webview<R>, cmd, response, callback, error| {
  969. if let Some(responder) = &custom_responder {
  970. (responder)(&webview, &cmd, &response, callback, error);
  971. }
  972. responder(webview, cmd, response, callback, error);
  973. },
  974. )))),
  975. request.cmd.clone(),
  976. request.callback,
  977. request.error,
  978. );
  979. #[cfg(mobile)]
  980. let app_handle = self.window.app_handle.clone();
  981. let message = InvokeMessage::new(
  982. self,
  983. manager.state(),
  984. request.cmd.to_string(),
  985. request.body,
  986. request.headers,
  987. );
  988. let acl_origin = if is_local {
  989. Origin::Local
  990. } else {
  991. Origin::Remote {
  992. domain: current_url
  993. .domain()
  994. .map(|d| d.to_string())
  995. .unwrap_or_default(),
  996. }
  997. };
  998. let resolved_acl = manager
  999. .runtime_authority
  1000. .resolve_access(&request.cmd, &message.webview.webview.label, &acl_origin)
  1001. .cloned();
  1002. let mut invoke = Invoke {
  1003. message,
  1004. resolver: resolver.clone(),
  1005. acl: resolved_acl,
  1006. };
  1007. if let Some((plugin, command_name)) = request.cmd.strip_prefix("plugin:").map(|raw_command| {
  1008. let mut tokens = raw_command.split('|');
  1009. // safe to unwrap: split always has a least one item
  1010. let plugin = tokens.next().unwrap();
  1011. let command = tokens.next().map(|c| c.to_string()).unwrap_or_default();
  1012. (plugin, command)
  1013. }) {
  1014. if request.cmd != crate::ipc::channel::FETCH_CHANNEL_DATA_COMMAND && invoke.acl.is_none() {
  1015. #[cfg(debug_assertions)]
  1016. {
  1017. invoke
  1018. .resolver
  1019. .reject(manager.runtime_authority.resolve_access_message(
  1020. plugin,
  1021. &command_name,
  1022. &invoke.message.webview.webview.label,
  1023. &acl_origin,
  1024. ));
  1025. }
  1026. #[cfg(not(debug_assertions))]
  1027. invoke
  1028. .resolver
  1029. .reject(format!("Command {} not allowed by ACL", request.cmd));
  1030. return;
  1031. }
  1032. invoke.message.command = command_name;
  1033. let command = invoke.message.command.clone();
  1034. #[cfg(mobile)]
  1035. let message = invoke.message.clone();
  1036. #[allow(unused_mut)]
  1037. let mut handled = manager.extend_api(plugin, invoke);
  1038. #[cfg(mobile)]
  1039. {
  1040. if !handled {
  1041. handled = true;
  1042. fn load_channels<R: Runtime>(payload: &serde_json::Value, webview: &Webview<R>) {
  1043. use std::str::FromStr;
  1044. if let serde_json::Value::Object(map) = payload {
  1045. for v in map.values() {
  1046. if let serde_json::Value::String(s) = v {
  1047. let _ = crate::ipc::JavaScriptChannelId::from_str(s)
  1048. .map(|id| id.channel_on(webview.clone()));
  1049. }
  1050. }
  1051. }
  1052. }
  1053. let payload = message.payload.into_json();
  1054. // initialize channels
  1055. load_channels(&payload, &message.webview);
  1056. let resolver_ = resolver.clone();
  1057. if let Err(e) = crate::plugin::mobile::run_command(
  1058. plugin,
  1059. &app_handle,
  1060. message.command,
  1061. payload,
  1062. move |response| match response {
  1063. Ok(r) => resolver_.resolve(r),
  1064. Err(e) => resolver_.reject(e),
  1065. },
  1066. ) {
  1067. resolver.reject(e.to_string());
  1068. return;
  1069. }
  1070. }
  1071. }
  1072. if !handled {
  1073. resolver.reject(format!("Command {command} not found"));
  1074. }
  1075. } else {
  1076. let command = invoke.message.command.clone();
  1077. let handled = manager.run_invoke_handler(invoke);
  1078. if !handled {
  1079. resolver.reject(format!("Command {command} not found"));
  1080. }
  1081. }
  1082. }
  1083. /// Evaluates JavaScript on this window.
  1084. pub fn eval(&self, js: &str) -> crate::Result<()> {
  1085. self.webview.dispatcher.eval_script(js).map_err(Into::into)
  1086. }
  1087. /// Register a JS event listener and return its identifier.
  1088. pub(crate) fn listen_js(
  1089. &self,
  1090. event: &str,
  1091. target: EventTarget,
  1092. handler: CallbackFn,
  1093. ) -> crate::Result<EventId> {
  1094. let listeners = self.manager().listeners();
  1095. let id = listeners.next_event_id();
  1096. self.eval(&crate::event::listen_js_script(
  1097. listeners.listeners_object_name(),
  1098. &serde_json::to_string(&target)?,
  1099. event,
  1100. id,
  1101. &format!("window['_{}']", handler.0),
  1102. ))?;
  1103. listeners.listen_js(event, self.label(), target, id);
  1104. Ok(id)
  1105. }
  1106. /// Unregister a JS event listener.
  1107. pub(crate) fn unlisten_js(&self, event: &str, id: EventId) -> crate::Result<()> {
  1108. let listeners = self.manager().listeners();
  1109. self.eval(&crate::event::unlisten_js_script(
  1110. listeners.listeners_object_name(),
  1111. event,
  1112. id,
  1113. ))?;
  1114. listeners.unlisten_js(id);
  1115. Ok(())
  1116. }
  1117. pub(crate) fn emit_js(&self, emit_args: &EmitArgs, target: &EventTarget) -> crate::Result<()> {
  1118. self.eval(&crate::event::emit_js_script(
  1119. self.manager().listeners().function_name(),
  1120. emit_args,
  1121. &serde_json::to_string(target)?,
  1122. )?)?;
  1123. Ok(())
  1124. }
  1125. /// Opens the developer tools window (Web Inspector).
  1126. /// The devtools is only enabled on debug builds or with the `devtools` feature flag.
  1127. ///
  1128. /// ## Platform-specific
  1129. ///
  1130. /// - **macOS:** Only supported on macOS 10.15+.
  1131. /// This is a private API on macOS, so you cannot use this if your application will be published on the App Store.
  1132. ///
  1133. /// # Examples
  1134. ///
  1135. #[cfg_attr(
  1136. feature = "unstable",
  1137. doc = r####"
  1138. ```rust,no_run
  1139. use tauri::Manager;
  1140. tauri::Builder::default()
  1141. .setup(|app| {
  1142. #[cfg(debug_assertions)]
  1143. app.get_webview("main").unwrap().open_devtools();
  1144. Ok(())
  1145. });
  1146. ```
  1147. "####
  1148. )]
  1149. #[cfg(any(debug_assertions, feature = "devtools"))]
  1150. #[cfg_attr(docsrs, doc(cfg(any(debug_assertions, feature = "devtools"))))]
  1151. pub fn open_devtools(&self) {
  1152. self.webview.dispatcher.open_devtools();
  1153. }
  1154. /// Closes the developer tools window (Web Inspector).
  1155. /// The devtools is only enabled on debug builds or with the `devtools` feature flag.
  1156. ///
  1157. /// ## Platform-specific
  1158. ///
  1159. /// - **macOS:** Only supported on macOS 10.15+.
  1160. /// This is a private API on macOS, so you cannot use this if your application will be published on the App Store.
  1161. /// - **Windows:** Unsupported.
  1162. ///
  1163. /// # Examples
  1164. ///
  1165. #[cfg_attr(
  1166. feature = "unstable",
  1167. doc = r####"
  1168. ```rust,no_run
  1169. use tauri::Manager;
  1170. tauri::Builder::default()
  1171. .setup(|app| {
  1172. #[cfg(debug_assertions)]
  1173. {
  1174. let webview = app.get_webview("main").unwrap();
  1175. webview.open_devtools();
  1176. std::thread::spawn(move || {
  1177. std::thread::sleep(std::time::Duration::from_secs(10));
  1178. webview.close_devtools();
  1179. });
  1180. }
  1181. Ok(())
  1182. });
  1183. ```
  1184. "####
  1185. )]
  1186. #[cfg(any(debug_assertions, feature = "devtools"))]
  1187. #[cfg_attr(docsrs, doc(cfg(any(debug_assertions, feature = "devtools"))))]
  1188. pub fn close_devtools(&self) {
  1189. self.webview.dispatcher.close_devtools();
  1190. }
  1191. /// Checks if the developer tools window (Web Inspector) is opened.
  1192. /// The devtools is only enabled on debug builds or with the `devtools` feature flag.
  1193. ///
  1194. /// ## Platform-specific
  1195. ///
  1196. /// - **macOS:** Only supported on macOS 10.15+.
  1197. /// This is a private API on macOS, so you cannot use this if your application will be published on the App Store.
  1198. /// - **Windows:** Unsupported.
  1199. ///
  1200. /// # Examples
  1201. ///
  1202. #[cfg_attr(
  1203. feature = "unstable",
  1204. doc = r####"
  1205. ```rust,no_run
  1206. use tauri::Manager;
  1207. tauri::Builder::default()
  1208. .setup(|app| {
  1209. #[cfg(debug_assertions)]
  1210. {
  1211. let webview = app.get_webview("main").unwrap();
  1212. if !webview.is_devtools_open() {
  1213. webview.open_devtools();
  1214. }
  1215. }
  1216. Ok(())
  1217. });
  1218. ```
  1219. "####
  1220. )]
  1221. #[cfg(any(debug_assertions, feature = "devtools"))]
  1222. #[cfg_attr(docsrs, doc(cfg(any(debug_assertions, feature = "devtools"))))]
  1223. pub fn is_devtools_open(&self) -> bool {
  1224. self
  1225. .webview
  1226. .dispatcher
  1227. .is_devtools_open()
  1228. .unwrap_or_default()
  1229. }
  1230. }
  1231. /// Event system APIs.
  1232. impl<R: Runtime> Webview<R> {
  1233. /// Listen to an event on this webview.
  1234. ///
  1235. /// # Examples
  1236. #[cfg_attr(
  1237. feature = "unstable",
  1238. doc = r####"
  1239. ```
  1240. use tauri::Manager;
  1241. tauri::Builder::default()
  1242. .setup(|app| {
  1243. let webview = app.get_webview("main").unwrap();
  1244. webview.listen("component-loaded", move |event| {
  1245. println!("window just loaded a component");
  1246. });
  1247. Ok(())
  1248. });
  1249. ```
  1250. "####
  1251. )]
  1252. pub fn listen<F>(&self, event: impl Into<String>, handler: F) -> EventId
  1253. where
  1254. F: Fn(Event) + Send + 'static,
  1255. {
  1256. self.window.manager.listen(
  1257. event.into(),
  1258. EventTarget::Webview {
  1259. label: self.label().to_string(),
  1260. },
  1261. handler,
  1262. )
  1263. }
  1264. /// Unlisten to an event on this webview.
  1265. ///
  1266. /// # Examples
  1267. #[cfg_attr(
  1268. feature = "unstable",
  1269. doc = r####"
  1270. ```
  1271. use tauri::Manager;
  1272. tauri::Builder::default()
  1273. .setup(|app| {
  1274. let webview = app.get_webview("main").unwrap();
  1275. let webview_ = webview.clone();
  1276. let handler = webview.listen("component-loaded", move |event| {
  1277. println!("webview just loaded a component");
  1278. // we no longer need to listen to the event
  1279. // we also could have used `webview.once` instead
  1280. webview_.unlisten(event.id());
  1281. });
  1282. // stop listening to the event when you do not need it anymore
  1283. webview.unlisten(handler);
  1284. Ok(())
  1285. });
  1286. ```
  1287. "####
  1288. )]
  1289. pub fn unlisten(&self, id: EventId) {
  1290. self.window.manager.unlisten(id)
  1291. }
  1292. /// Listen to an event on this webview only once.
  1293. ///
  1294. /// See [`Self::listen`] for more information.
  1295. pub fn once<F>(&self, event: impl Into<String>, handler: F)
  1296. where
  1297. F: FnOnce(Event) + Send + 'static,
  1298. {
  1299. self.window.manager.once(
  1300. event.into(),
  1301. EventTarget::Webview {
  1302. label: self.label().to_string(),
  1303. },
  1304. handler,
  1305. )
  1306. }
  1307. }
  1308. impl<R: Runtime> Manager<R> for Webview<R> {}
  1309. impl<R: Runtime> ManagerBase<R> for Webview<R> {
  1310. fn manager(&self) -> &AppManager<R> {
  1311. &self.window.manager
  1312. }
  1313. fn manager_owned(&self) -> Arc<AppManager<R>> {
  1314. self.window.manager.clone()
  1315. }
  1316. fn runtime(&self) -> RuntimeOrDispatch<'_, R> {
  1317. self.window.app_handle.runtime()
  1318. }
  1319. fn managed_app_handle(&self) -> &AppHandle<R> {
  1320. &self.window.app_handle
  1321. }
  1322. }
  1323. impl<'de, R: Runtime> CommandArg<'de, R> for Webview<R> {
  1324. /// Grabs the [`Webview`] from the [`CommandItem`]. This will never fail.
  1325. fn from_command(command: CommandItem<'de, R>) -> Result<Self, InvokeError> {
  1326. Ok(command.message.webview())
  1327. }
  1328. }
  1329. #[cfg(test)]
  1330. mod tests {
  1331. #[test]
  1332. fn webview_is_send_sync() {
  1333. crate::test_utils::assert_send::<super::Webview>();
  1334. crate::test_utils::assert_sync::<super::Webview>();
  1335. }
  1336. }