mod.rs 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542
  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, WebviewEvent},
  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().app.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. /// Set a proxy URL for the WebView for all network requests.
  700. ///
  701. /// Must be either a `http://` or a `socks5://` URL.
  702. ///
  703. /// ## Platform-specific
  704. ///
  705. /// - **macOS**: Requires the `macos-proxy` feature flag and only compiles for macOS 14+.
  706. #[must_use]
  707. pub fn proxy_url(mut self, url: Url) -> Self {
  708. self.webview_attributes.proxy_url = Some(url);
  709. self
  710. }
  711. /// Enable or disable transparency for the WebView.
  712. #[cfg(any(not(target_os = "macos"), feature = "macos-private-api"))]
  713. #[cfg_attr(
  714. docsrs,
  715. doc(cfg(any(not(target_os = "macos"), feature = "macos-private-api")))
  716. )]
  717. #[must_use]
  718. pub fn transparent(mut self, transparent: bool) -> Self {
  719. self.webview_attributes.transparent = transparent;
  720. self
  721. }
  722. /// Sets the webview to automatically grow and shrink its size and position when the parent window resizes.
  723. #[must_use]
  724. pub fn auto_resize(mut self) -> Self {
  725. self.webview_attributes.auto_resize = true;
  726. self
  727. }
  728. }
  729. /// Webview.
  730. #[default_runtime(crate::Wry, wry)]
  731. pub struct Webview<R: Runtime> {
  732. window_label: Arc<Mutex<String>>,
  733. /// The manager to associate this webview with.
  734. pub(crate) manager: Arc<AppManager<R>>,
  735. pub(crate) app_handle: AppHandle<R>,
  736. /// The webview created by the runtime.
  737. pub(crate) webview: DetachedWebview<EventLoopMessage, R>,
  738. }
  739. impl<R: Runtime> std::fmt::Debug for Webview<R> {
  740. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  741. f.debug_struct("Window")
  742. .field("window_label", &self.window_label)
  743. .field("webview", &self.webview)
  744. .finish()
  745. }
  746. }
  747. impl<R: Runtime> Clone for Webview<R> {
  748. fn clone(&self) -> Self {
  749. Self {
  750. window_label: self.window_label.clone(),
  751. manager: self.manager.clone(),
  752. app_handle: self.app_handle.clone(),
  753. webview: self.webview.clone(),
  754. }
  755. }
  756. }
  757. impl<R: Runtime> Hash for Webview<R> {
  758. /// Only use the [`Webview`]'s label to represent its hash.
  759. fn hash<H: Hasher>(&self, state: &mut H) {
  760. self.webview.label.hash(state)
  761. }
  762. }
  763. impl<R: Runtime> Eq for Webview<R> {}
  764. impl<R: Runtime> PartialEq for Webview<R> {
  765. /// Only use the [`Webview`]'s label to compare equality.
  766. fn eq(&self, other: &Self) -> bool {
  767. self.webview.label.eq(&other.webview.label)
  768. }
  769. }
  770. /// Base webview functions.
  771. impl<R: Runtime> Webview<R> {
  772. /// Create a new webview that is attached to the window.
  773. pub(crate) fn new(window: Window<R>, webview: DetachedWebview<EventLoopMessage, R>) -> Self {
  774. Self {
  775. window_label: Arc::new(Mutex::new(window.label().into())),
  776. manager: window.manager.clone(),
  777. app_handle: window.app_handle.clone(),
  778. webview,
  779. }
  780. }
  781. /// Initializes a webview builder with the given window label and URL to load on the webview.
  782. ///
  783. /// Data URLs are only supported with the `webview-data-url` feature flag.
  784. #[cfg(feature = "unstable")]
  785. #[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
  786. pub fn builder<L: Into<String>>(label: L, url: WebviewUrl) -> WebviewBuilder<R> {
  787. WebviewBuilder::new(label.into(), url)
  788. }
  789. /// Runs the given closure on the main thread.
  790. pub fn run_on_main_thread<F: FnOnce() + Send + 'static>(&self, f: F) -> crate::Result<()> {
  791. self
  792. .webview
  793. .dispatcher
  794. .run_on_main_thread(f)
  795. .map_err(Into::into)
  796. }
  797. /// The webview label.
  798. pub fn label(&self) -> &str {
  799. &self.webview.label
  800. }
  801. /// Registers a window event listener.
  802. pub fn on_webview_event<F: Fn(&WebviewEvent) + Send + 'static>(&self, f: F) {
  803. self
  804. .webview
  805. .dispatcher
  806. .on_webview_event(move |event| f(&event.clone().into()));
  807. }
  808. }
  809. /// Desktop webview setters and actions.
  810. #[cfg(desktop)]
  811. impl<R: Runtime> Webview<R> {
  812. /// Opens the dialog to prints the contents of the webview.
  813. /// Currently only supported on macOS on `wry`.
  814. /// `window.print()` works on all platforms.
  815. pub fn print(&self) -> crate::Result<()> {
  816. self.webview.dispatcher.print().map_err(Into::into)
  817. }
  818. /// Closes this webview.
  819. pub fn close(&self) -> crate::Result<()> {
  820. let window = self.window();
  821. if window.is_webview_window {
  822. window.close()
  823. } else {
  824. self.webview.dispatcher.close()?;
  825. self.manager().on_webview_close(self.label());
  826. Ok(())
  827. }
  828. }
  829. /// Resizes this webview.
  830. pub fn set_size<S: Into<Size>>(&self, size: S) -> crate::Result<()> {
  831. let window = self.window();
  832. if window.is_webview_window {
  833. window.set_size(size.into())
  834. } else {
  835. self
  836. .webview
  837. .dispatcher
  838. .set_size(size.into())
  839. .map_err(Into::into)
  840. }
  841. }
  842. /// Sets this webviews's position.
  843. pub fn set_position<Pos: Into<Position>>(&self, position: Pos) -> crate::Result<()> {
  844. let window = self.window();
  845. if window.is_webview_window {
  846. window.set_position(position.into())
  847. } else {
  848. self
  849. .webview
  850. .dispatcher
  851. .set_position(position.into())
  852. .map_err(Into::into)
  853. }
  854. }
  855. /// Focus the webview.
  856. pub fn set_focus(&self) -> crate::Result<()> {
  857. self.webview.dispatcher.set_focus().map_err(Into::into)
  858. }
  859. /// Move the webview to the given window.
  860. pub fn reparent(&self, window: &Window<R>) -> crate::Result<()> {
  861. let current_window = self.window();
  862. if !current_window.is_webview_window {
  863. self.webview.dispatcher.reparent(window.window.id)?;
  864. }
  865. Ok(())
  866. }
  867. /// Returns the webview position.
  868. ///
  869. /// - 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.
  870. /// - For webview window, returns the inner position of the window.
  871. pub fn position(&self) -> crate::Result<PhysicalPosition<i32>> {
  872. let window = self.window();
  873. if window.is_webview_window {
  874. window.inner_position()
  875. } else {
  876. self.webview.dispatcher.position().map_err(Into::into)
  877. }
  878. }
  879. /// Returns the physical size of the webviews's client area.
  880. pub fn size(&self) -> crate::Result<PhysicalSize<u32>> {
  881. let window = self.window();
  882. if window.is_webview_window {
  883. window.inner_size()
  884. } else {
  885. self.webview.dispatcher.size().map_err(Into::into)
  886. }
  887. }
  888. }
  889. /// Webview APIs.
  890. impl<R: Runtime> Webview<R> {
  891. /// The window that is hosting this webview.
  892. pub fn window(&self) -> Window<R> {
  893. self
  894. .manager
  895. .get_window(&self.window_label.lock().unwrap())
  896. .expect("could not locate webview parent window")
  897. }
  898. pub(crate) fn window_label(&self) -> String {
  899. self.window_label.lock().unwrap().clone()
  900. }
  901. /// Executes a closure, providing it with the webview handle that is specific to the current platform.
  902. ///
  903. /// The closure is executed on the main thread.
  904. ///
  905. /// # Examples
  906. ///
  907. #[cfg_attr(
  908. feature = "unstable",
  909. doc = r####"
  910. ```rust,no_run
  911. #[cfg(target_os = "macos")]
  912. #[macro_use]
  913. extern crate objc;
  914. use tauri::Manager;
  915. fn main() {
  916. tauri::Builder::default()
  917. .setup(|app| {
  918. let main_webview = app.get_webview("main").unwrap();
  919. main_webview.with_webview(|webview| {
  920. #[cfg(target_os = "linux")]
  921. {
  922. // see https://docs.rs/webkit2gtk/2.0.0/webkit2gtk/struct.WebView.html
  923. // and https://docs.rs/webkit2gtk/2.0.0/webkit2gtk/trait.WebViewExt.html
  924. use webkit2gtk::WebViewExt;
  925. webview.inner().set_zoom_level(4.);
  926. }
  927. #[cfg(windows)]
  928. unsafe {
  929. // see https://docs.rs/webview2-com/0.19.1/webview2_com/Microsoft/Web/WebView2/Win32/struct.ICoreWebView2Controller.html
  930. webview.controller().SetZoomFactor(4.).unwrap();
  931. }
  932. #[cfg(target_os = "macos")]
  933. unsafe {
  934. let () = msg_send![webview.inner(), setPageZoom: 4.];
  935. let () = msg_send![webview.controller(), removeAllUserScripts];
  936. let bg_color: cocoa::base::id = msg_send![class!(NSColor), colorWithDeviceRed:0.5 green:0.2 blue:0.4 alpha:1.];
  937. let () = msg_send![webview.ns_window(), setBackgroundColor: bg_color];
  938. }
  939. #[cfg(target_os = "android")]
  940. {
  941. use jni::objects::JValue;
  942. webview.jni_handle().exec(|env, _, webview| {
  943. env.call_method(webview, "zoomBy", "(F)V", &[JValue::Float(4.)]).unwrap();
  944. })
  945. }
  946. });
  947. Ok(())
  948. });
  949. }
  950. ```
  951. "####
  952. )]
  953. #[cfg(feature = "wry")]
  954. #[cfg_attr(docsrs, doc(feature = "wry"))]
  955. pub fn with_webview<F: FnOnce(PlatformWebview) + Send + 'static>(
  956. &self,
  957. f: F,
  958. ) -> crate::Result<()> {
  959. self
  960. .webview
  961. .dispatcher
  962. .with_webview(|w| f(PlatformWebview(*w.downcast().unwrap())))
  963. .map_err(Into::into)
  964. }
  965. /// Returns the current url of the webview.
  966. // TODO: in v2, change this type to Result
  967. pub fn url(&self) -> Url {
  968. self.webview.dispatcher.url().unwrap()
  969. }
  970. /// Navigates the webview to the defined url.
  971. pub fn navigate(&mut self, url: Url) {
  972. self.webview.dispatcher.navigate(url).unwrap();
  973. }
  974. fn is_local_url(&self, current_url: &Url) -> bool {
  975. // if from `tauri://` custom protocol
  976. ({
  977. let protocol_url = self.manager().protocol_url();
  978. current_url.scheme() == protocol_url.scheme()
  979. && current_url.domain() == protocol_url.domain()
  980. }) ||
  981. // or if relative to `devUrl` or `frontendDist`
  982. self
  983. .manager()
  984. .get_url()
  985. .make_relative(current_url)
  986. .is_some()
  987. // or from a custom protocol registered by the user
  988. || ({
  989. let scheme = current_url.scheme();
  990. let protocols = self.manager().webview.uri_scheme_protocols.lock().unwrap();
  991. #[cfg(all(not(windows), not(target_os = "android")))]
  992. let local = protocols.contains_key(scheme);
  993. // on window and android, custom protocols are `http://<protocol-name>.path/to/route`
  994. // so we check using the first part of the domain
  995. #[cfg(any(windows, target_os = "android"))]
  996. let local = {
  997. let protocol_url = self.manager().protocol_url();
  998. let maybe_protocol = current_url
  999. .domain()
  1000. .and_then(|d| d .split_once('.'))
  1001. .unwrap_or_default()
  1002. .0;
  1003. protocols.contains_key(maybe_protocol) && scheme == protocol_url.scheme()
  1004. };
  1005. local
  1006. })
  1007. }
  1008. /// Handles this window receiving an [`InvokeRequest`].
  1009. pub fn on_message(self, request: InvokeRequest, responder: Box<OwnedInvokeResponder<R>>) {
  1010. let manager = self.manager_owned();
  1011. let current_url = self.url();
  1012. let is_local = self.is_local_url(&current_url);
  1013. let custom_responder = self.manager().webview.invoke_responder.clone();
  1014. let resolver = InvokeResolver::new(
  1015. self.clone(),
  1016. Arc::new(Mutex::new(Some(Box::new(
  1017. #[allow(unused_variables)]
  1018. move |webview: Webview<R>, cmd, response, callback, error| {
  1019. if let Some(responder) = &custom_responder {
  1020. (responder)(&webview, &cmd, &response, callback, error);
  1021. }
  1022. responder(webview, cmd, response, callback, error);
  1023. },
  1024. )))),
  1025. request.cmd.clone(),
  1026. request.callback,
  1027. request.error,
  1028. );
  1029. #[cfg(mobile)]
  1030. let app_handle = self.app_handle.clone();
  1031. let message = InvokeMessage::new(
  1032. self,
  1033. manager.state(),
  1034. request.cmd.to_string(),
  1035. request.body,
  1036. request.headers,
  1037. );
  1038. let acl_origin = if is_local {
  1039. Origin::Local
  1040. } else {
  1041. Origin::Remote {
  1042. url: current_url.to_string(),
  1043. }
  1044. };
  1045. let resolved_acl = manager
  1046. .runtime_authority
  1047. .lock()
  1048. .unwrap()
  1049. .resolve_access(
  1050. &request.cmd,
  1051. message.webview.window().label(),
  1052. message.webview.label(),
  1053. &acl_origin,
  1054. )
  1055. .cloned();
  1056. let mut invoke = Invoke {
  1057. message,
  1058. resolver: resolver.clone(),
  1059. acl: resolved_acl,
  1060. };
  1061. if let Some((plugin, command_name)) = request.cmd.strip_prefix("plugin:").map(|raw_command| {
  1062. let mut tokens = raw_command.split('|');
  1063. // safe to unwrap: split always has a least one item
  1064. let plugin = tokens.next().unwrap();
  1065. let command = tokens.next().map(|c| c.to_string()).unwrap_or_default();
  1066. (plugin, command)
  1067. }) {
  1068. if request.cmd != crate::ipc::channel::FETCH_CHANNEL_DATA_COMMAND && invoke.acl.is_none() {
  1069. #[cfg(debug_assertions)]
  1070. {
  1071. invoke.resolver.reject(
  1072. manager
  1073. .runtime_authority
  1074. .lock()
  1075. .unwrap()
  1076. .resolve_access_message(
  1077. plugin,
  1078. &command_name,
  1079. invoke.message.webview.window().label(),
  1080. invoke.message.webview.label(),
  1081. &acl_origin,
  1082. ),
  1083. );
  1084. }
  1085. #[cfg(not(debug_assertions))]
  1086. invoke
  1087. .resolver
  1088. .reject(format!("Command {} not allowed by ACL", request.cmd));
  1089. return;
  1090. }
  1091. invoke.message.command = command_name;
  1092. let command = invoke.message.command.clone();
  1093. #[cfg(mobile)]
  1094. let message = invoke.message.clone();
  1095. #[allow(unused_mut)]
  1096. let mut handled = manager.extend_api(plugin, invoke);
  1097. #[cfg(mobile)]
  1098. {
  1099. if !handled {
  1100. handled = true;
  1101. fn load_channels<R: Runtime>(payload: &serde_json::Value, webview: &Webview<R>) {
  1102. use std::str::FromStr;
  1103. if let serde_json::Value::Object(map) = payload {
  1104. for v in map.values() {
  1105. if let serde_json::Value::String(s) = v {
  1106. let _ = crate::ipc::JavaScriptChannelId::from_str(s)
  1107. .map(|id| id.channel_on(webview.clone()));
  1108. }
  1109. }
  1110. }
  1111. }
  1112. let payload = message.payload.into_json();
  1113. // initialize channels
  1114. load_channels(&payload, &message.webview);
  1115. let resolver_ = resolver.clone();
  1116. if let Err(e) = crate::plugin::mobile::run_command(
  1117. plugin,
  1118. &app_handle,
  1119. heck::AsLowerCamelCase(message.command).to_string(),
  1120. payload,
  1121. move |response| match response {
  1122. Ok(r) => resolver_.resolve(r),
  1123. Err(e) => resolver_.reject(e),
  1124. },
  1125. ) {
  1126. resolver.reject(e.to_string());
  1127. return;
  1128. }
  1129. }
  1130. }
  1131. if !handled {
  1132. resolver.reject(format!("Command {command} not found"));
  1133. }
  1134. } else {
  1135. let command = invoke.message.command.clone();
  1136. let handled = manager.run_invoke_handler(invoke);
  1137. if !handled {
  1138. resolver.reject(format!("Command {command} not found"));
  1139. }
  1140. }
  1141. }
  1142. /// Evaluates JavaScript on this window.
  1143. pub fn eval(&self, js: &str) -> crate::Result<()> {
  1144. self.webview.dispatcher.eval_script(js).map_err(Into::into)
  1145. }
  1146. /// Register a JS event listener and return its identifier.
  1147. pub(crate) fn listen_js(
  1148. &self,
  1149. event: &str,
  1150. target: EventTarget,
  1151. handler: CallbackFn,
  1152. ) -> crate::Result<EventId> {
  1153. let listeners = self.manager().listeners();
  1154. let id = listeners.next_event_id();
  1155. self.eval(&crate::event::listen_js_script(
  1156. listeners.listeners_object_name(),
  1157. &serde_json::to_string(&target)?,
  1158. event,
  1159. id,
  1160. &format!("window['_{}']", handler.0),
  1161. ))?;
  1162. listeners.listen_js(event, self.label(), target, id);
  1163. Ok(id)
  1164. }
  1165. /// Unregister a JS event listener.
  1166. pub(crate) fn unlisten_js(&self, event: &str, id: EventId) -> crate::Result<()> {
  1167. let listeners = self.manager().listeners();
  1168. self.eval(&crate::event::unlisten_js_script(
  1169. listeners.listeners_object_name(),
  1170. event,
  1171. id,
  1172. ))?;
  1173. listeners.unlisten_js(id);
  1174. Ok(())
  1175. }
  1176. pub(crate) fn emit_js(&self, emit_args: &EmitArgs, target: &EventTarget) -> crate::Result<()> {
  1177. self.eval(&crate::event::emit_js_script(
  1178. self.manager().listeners().function_name(),
  1179. emit_args,
  1180. &serde_json::to_string(target)?,
  1181. )?)?;
  1182. Ok(())
  1183. }
  1184. /// Opens the developer tools window (Web Inspector).
  1185. /// The devtools is only enabled on debug builds or with the `devtools` feature flag.
  1186. ///
  1187. /// ## Platform-specific
  1188. ///
  1189. /// - **macOS:** Only supported on macOS 10.15+.
  1190. /// This is a private API on macOS, so you cannot use this if your application will be published on the App Store.
  1191. ///
  1192. /// # Examples
  1193. ///
  1194. #[cfg_attr(
  1195. feature = "unstable",
  1196. doc = r####"
  1197. ```rust,no_run
  1198. use tauri::Manager;
  1199. tauri::Builder::default()
  1200. .setup(|app| {
  1201. #[cfg(debug_assertions)]
  1202. app.get_webview("main").unwrap().open_devtools();
  1203. Ok(())
  1204. });
  1205. ```
  1206. "####
  1207. )]
  1208. #[cfg(any(debug_assertions, feature = "devtools"))]
  1209. #[cfg_attr(docsrs, doc(cfg(any(debug_assertions, feature = "devtools"))))]
  1210. pub fn open_devtools(&self) {
  1211. self.webview.dispatcher.open_devtools();
  1212. }
  1213. /// Closes the developer tools window (Web Inspector).
  1214. /// The devtools is only enabled on debug builds or with the `devtools` feature flag.
  1215. ///
  1216. /// ## Platform-specific
  1217. ///
  1218. /// - **macOS:** Only supported on macOS 10.15+.
  1219. /// This is a private API on macOS, so you cannot use this if your application will be published on the App Store.
  1220. /// - **Windows:** Unsupported.
  1221. ///
  1222. /// # Examples
  1223. ///
  1224. #[cfg_attr(
  1225. feature = "unstable",
  1226. doc = r####"
  1227. ```rust,no_run
  1228. use tauri::Manager;
  1229. tauri::Builder::default()
  1230. .setup(|app| {
  1231. #[cfg(debug_assertions)]
  1232. {
  1233. let webview = app.get_webview("main").unwrap();
  1234. webview.open_devtools();
  1235. std::thread::spawn(move || {
  1236. std::thread::sleep(std::time::Duration::from_secs(10));
  1237. webview.close_devtools();
  1238. });
  1239. }
  1240. Ok(())
  1241. });
  1242. ```
  1243. "####
  1244. )]
  1245. #[cfg(any(debug_assertions, feature = "devtools"))]
  1246. #[cfg_attr(docsrs, doc(cfg(any(debug_assertions, feature = "devtools"))))]
  1247. pub fn close_devtools(&self) {
  1248. self.webview.dispatcher.close_devtools();
  1249. }
  1250. /// Checks if the developer tools window (Web Inspector) is opened.
  1251. /// The devtools is only enabled on debug builds or with the `devtools` feature flag.
  1252. ///
  1253. /// ## Platform-specific
  1254. ///
  1255. /// - **macOS:** Only supported on macOS 10.15+.
  1256. /// This is a private API on macOS, so you cannot use this if your application will be published on the App Store.
  1257. /// - **Windows:** Unsupported.
  1258. ///
  1259. /// # Examples
  1260. ///
  1261. #[cfg_attr(
  1262. feature = "unstable",
  1263. doc = r####"
  1264. ```rust,no_run
  1265. use tauri::Manager;
  1266. tauri::Builder::default()
  1267. .setup(|app| {
  1268. #[cfg(debug_assertions)]
  1269. {
  1270. let webview = app.get_webview("main").unwrap();
  1271. if !webview.is_devtools_open() {
  1272. webview.open_devtools();
  1273. }
  1274. }
  1275. Ok(())
  1276. });
  1277. ```
  1278. "####
  1279. )]
  1280. #[cfg(any(debug_assertions, feature = "devtools"))]
  1281. #[cfg_attr(docsrs, doc(cfg(any(debug_assertions, feature = "devtools"))))]
  1282. pub fn is_devtools_open(&self) -> bool {
  1283. self
  1284. .webview
  1285. .dispatcher
  1286. .is_devtools_open()
  1287. .unwrap_or_default()
  1288. }
  1289. }
  1290. /// Event system APIs.
  1291. impl<R: Runtime> Webview<R> {
  1292. /// Listen to an event on this webview.
  1293. ///
  1294. /// # Examples
  1295. #[cfg_attr(
  1296. feature = "unstable",
  1297. doc = r####"
  1298. ```
  1299. use tauri::Manager;
  1300. tauri::Builder::default()
  1301. .setup(|app| {
  1302. let webview = app.get_webview("main").unwrap();
  1303. webview.listen("component-loaded", move |event| {
  1304. println!("window just loaded a component");
  1305. });
  1306. Ok(())
  1307. });
  1308. ```
  1309. "####
  1310. )]
  1311. pub fn listen<F>(&self, event: impl Into<String>, handler: F) -> EventId
  1312. where
  1313. F: Fn(Event) + Send + 'static,
  1314. {
  1315. self.manager.listen(
  1316. event.into(),
  1317. EventTarget::Webview {
  1318. label: self.label().to_string(),
  1319. },
  1320. handler,
  1321. )
  1322. }
  1323. /// Unlisten to an event on this webview.
  1324. ///
  1325. /// # Examples
  1326. #[cfg_attr(
  1327. feature = "unstable",
  1328. doc = r####"
  1329. ```
  1330. use tauri::Manager;
  1331. tauri::Builder::default()
  1332. .setup(|app| {
  1333. let webview = app.get_webview("main").unwrap();
  1334. let webview_ = webview.clone();
  1335. let handler = webview.listen("component-loaded", move |event| {
  1336. println!("webview just loaded a component");
  1337. // we no longer need to listen to the event
  1338. // we also could have used `webview.once` instead
  1339. webview_.unlisten(event.id());
  1340. });
  1341. // stop listening to the event when you do not need it anymore
  1342. webview.unlisten(handler);
  1343. Ok(())
  1344. });
  1345. ```
  1346. "####
  1347. )]
  1348. pub fn unlisten(&self, id: EventId) {
  1349. self.manager.unlisten(id)
  1350. }
  1351. /// Listen to an event on this webview only once.
  1352. ///
  1353. /// See [`Self::listen`] for more information.
  1354. pub fn once<F>(&self, event: impl Into<String>, handler: F) -> EventId
  1355. where
  1356. F: FnOnce(Event) + Send + 'static,
  1357. {
  1358. self.manager.once(
  1359. event.into(),
  1360. EventTarget::Webview {
  1361. label: self.label().to_string(),
  1362. },
  1363. handler,
  1364. )
  1365. }
  1366. }
  1367. impl<R: Runtime> Manager<R> for Webview<R> {}
  1368. impl<R: Runtime> ManagerBase<R> for Webview<R> {
  1369. fn manager(&self) -> &AppManager<R> {
  1370. &self.manager
  1371. }
  1372. fn manager_owned(&self) -> Arc<AppManager<R>> {
  1373. self.manager.clone()
  1374. }
  1375. fn runtime(&self) -> RuntimeOrDispatch<'_, R> {
  1376. self.app_handle.runtime()
  1377. }
  1378. fn managed_app_handle(&self) -> &AppHandle<R> {
  1379. &self.app_handle
  1380. }
  1381. }
  1382. impl<'de, R: Runtime> CommandArg<'de, R> for Webview<R> {
  1383. /// Grabs the [`Webview`] from the [`CommandItem`]. This will never fail.
  1384. fn from_command(command: CommandItem<'de, R>) -> Result<Self, InvokeError> {
  1385. Ok(command.message.webview())
  1386. }
  1387. }
  1388. #[cfg(test)]
  1389. mod tests {
  1390. #[test]
  1391. fn webview_is_send_sync() {
  1392. crate::test_utils::assert_send::<super::Webview>();
  1393. crate::test_utils::assert_sync::<super::Webview>();
  1394. }
  1395. }