乐闻世界logo
搜索文章和话题

How to open webpage when cliking on the menu in Tauri?

1个答案

1

When developing desktop applications with Tauri, opening a web page is a common requirement. Tauri provides multiple approaches to achieve this, and I will walk through how to open a web page by clicking a menu item.

First, define menu items in your Tauri project and set up an event handler that triggers when the user clicks the menu item.

Here is a basic example demonstrating how to open a web page using Tauri's menu functionality:

rust
#![cfg_attr( all(not(debug_assertions), target_os = "windows"), windows_subsystem = "windows" )] use tauri::{CustomMenuItem, Menu, MenuItem, Submenu, Window}; fn main() { tauri::Builder::default() .menu(build_menu()) .invoke_handler(tauri::generate_handler![open_browser]) .run(tauri::generate_context!()) .expect("error while running tauri application"); } fn build_menu() -> Menu { let open_web = CustomMenuItem::new("open_browser".to_string(), "Open Web Page"); let submenu = Submenu::new("Options", Menu::new().add_item(open_web)); let menu = Menu::new() .add_native_item(MenuItem::Copy) .add_submenu(submenu); menu } #[tauri::command] fn open_browser(window: Window) { // Open the web page in the default browser if let Err(e) = window.open("https://www.example.com".into()) { println!("Failed to open web page: {}", e); } }

In this example, we first define a menu item open_web and add it to a submenu. The open_browser menu item is linked to a command that invokes the open_browser function upon click.

The open_browser function uses the window.open method to open the specified URL. In this example, we use "https://www.example.com", but you can replace it with any URL you prefer.

This approach offers simplicity and ease of implementation while preserving the application's security and performance. By leveraging the system's default browser to open web pages, we avoid embedding a full browser within the application, thereby reducing resource consumption.

This covers the fundamental approach to opening web pages using Tauri.

2024年7月9日 14:27 回复

你的答案