Skip to content

Commit ddaabda

Browse files
authored
feat: expose WebviewWinowBuilder::on_download (#9922)
* feat: expose `WebviewWinowBuilder::on_download` closes #9921 * fix tests
1 parent 3cca5c2 commit ddaabda

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed
+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"tauri": "patch:feat"
3+
---
4+
5+
Add `WebviewWindowBuilder::on_download`.

core/tauri/src/webview/webview_window.rs

+50
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,8 @@ use tauri_macros::default_runtime;
4444
#[cfg(windows)]
4545
use windows::Win32::Foundation::HWND;
4646

47+
use super::DownloadEvent;
48+
4749
/// A builder for [`WebviewWindow`], a window that hosts a single webview.
4850
pub struct WebviewWindowBuilder<'a, R: Runtime, M: Manager<R>> {
4951
window_builder: WindowBuilder<'a, R, M>,
@@ -263,6 +265,54 @@ tauri::Builder::default()
263265
self
264266
}
265267

268+
/// Set a download event handler to be notified when a download is requested or finished.
269+
///
270+
/// Returning `false` prevents the download from happening on a [`DownloadEvent::Requested`] event.
271+
///
272+
/// # Examples
273+
///
274+
#[cfg_attr(
275+
feature = "unstable",
276+
doc = r####"
277+
```rust,no_run
278+
use tauri::{
279+
utils::config::{Csp, CspDirectiveSources, WebviewUrl},
280+
webview::{DownloadEvent, WebviewWindowBuilder},
281+
};
282+
283+
tauri::Builder::default()
284+
.setup(|app| {
285+
let handle = app.handle();
286+
let webview_window = WebviewWindowBuilder::new(handle, "core", WebviewUrl::App("index.html".into()))
287+
.on_download(|webview, event| {
288+
match event {
289+
DownloadEvent::Requested { url, destination } => {
290+
println!("downloading {}", url);
291+
*destination = "/home/tauri/target/path".into();
292+
}
293+
DownloadEvent::Finished { url, path, success } => {
294+
println!("downloaded {} to {:?}, success: {}", url, path, success);
295+
}
296+
_ => (),
297+
}
298+
// let the download start
299+
true
300+
})
301+
.build()?;
302+
303+
Ok(())
304+
});
305+
```
306+
"####
307+
)]
308+
pub fn on_download<F: Fn(Webview<R>, DownloadEvent<'_>) -> bool + Send + Sync + 'static>(
309+
mut self,
310+
f: F,
311+
) -> Self {
312+
self.webview_builder.download_handler.replace(Arc::new(f));
313+
self
314+
}
315+
266316
/// Defines a closure to be executed when a page load event is triggered.
267317
/// The event can be either [`tauri_runtime::webview::PageLoadEvent::Started`] if the page has started loading
268318
/// or [`tauri_runtime::webview::PageLoadEvent::Finished`] when the page finishes loading.

0 commit comments

Comments
 (0)