如何在Tauri应用中禁用WebView2下载进度条
问题描述
我使用Tauri工具链将单页前端网站转换为桌面应用,在应用内下载图片或其他文件时,右上角会显示下载进度条,需要禁用该进度条。查阅WebView2文档得知,将CoreWebView2DownloadStartingEventArgs.Handled属性设置为true即可隐藏下载进度对话框,但不清楚如何在Tauri应用源码中设置该属性。附上项目代码,希望能指导如何设置该属性以隐藏进度条。
项目代码
HTML文件
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <img src="https://cdn.pixabay.com/photo/2014/02/27/16/10/flowers-276014_960_720.jpg" alt="W3Schools" width="500"> <a href="https://cdn.pixabay.com/photo/2014/02/27/16/10/flowers-276014_960_720.jpg" download="image.jpg"> <button type="button">Download</button> </a> </body> </html>
Rust主文件
#![cfg_attr( all(not(debug_assertions), target_os = "windows"), windows_subsystem = "windows" )] fn main() { tauri::Builder::default() .run(tauri::generate_context!()) .expect("error while running tauri application"); }
tauri.conf配置文件
{ "build": { "beforeBuildCommand": "", "beforeDevCommand": "", "devPath": "../assets", "distDir": "../assets" }, "package": { "productName": "test", "version": "0.1.0" }, "tauri": { "allowlist": { "all": true }, "bundle": { "active": true, "category": "DeveloperTool", "copyright": "", "deb": { "depends": [] }, "externalBin": [], "icon": [ "icons/32x32.png", "icons/128x128.png", "icons/128x128@2x.png", "icons/icon.icns", "icons/icon.ico" ], "identifier": "com.tauri.dev", "longDescription": "", "macOS": { "entitlements": null, "exceptionDomain": "", "frameworks": [], "providerShortName": null, "signingIdentity": null }, "resources": [], "shortDescription": "", "targets": "all", "windows": { "certificateThumbprint": null, "digestAlgorithm": "sha256", "timestampUrl": "" } }, "security": { "csp": null }, "updater": { "active": false }, "windows": [ { "fullscreen": false, "height": 600, "resizable": true, "title": "Test", "width": 800 } ] } }
解决方案
要在Tauri中禁用WebView2的下载进度条,需通过Tauri的on_webview_ready钩子获取WebView2实例,订阅download_starting事件并将Handled属性设为true。修改后的Rust主文件如下:
#![cfg_attr( all(not(debug_assertions), target_os = "windows"), windows_subsystem = "windows" )] fn main() { tauri::Builder::default() .on_webview_ready(|window| { #[cfg(target_os = "windows")] if let Some(webview) = window.webview() { webview.on_download_starting(|args| { args.set_handled(true); // 若需自定义下载逻辑,可在此添加代码 // 比如调用Tauri的文件系统API手动处理下载 }); } }) .run(tauri::generate_context!()) .expect("error while running tauri application"); }
说明
on_webview_ready钩子确保WebView实例初始化完成后再执行后续逻辑。#[cfg(target_os = "windows")]限定仅在Windows平台执行该逻辑(WebView2为Windows专属组件)。- 订阅
download_starting事件后,调用args.set_handled(true)即可阻止WebView2显示默认下载进度条。 - 若需要自定义下载行为,可在
on_download_starting回调内添加自定义逻辑,比如使用Tauri的fsAPI完成文件保存。
内容的提问来源于stack exchange,提问作者Kailash Kumaravel
相关产品推荐
相关产品推荐

