Tauri v2 自定义菜单项

// Adding a webview navigation shortcut to the native app menu.

// 将 webview 导航快捷键添加到原生应用菜单。

I’ve been trying to add a custom native Settings... menu item to my Tauri v2 app. When clicking this menu item, I wanted the frontend webview to navigate to the /settings page.

我一直在尝试为我的 Tauri v2 应用添加一个原生的自定义 Settings... 菜单项。点击该菜单项时,我希望前端 webview 跳转到 /settings 页面。

After a few days of struggling with this, I’ve finally got it working! Here’s how I did it:

经过几天的努力,我终于搞定了!以下是我的做法:

Overview

概述

In order to achieve this, we need to implement a custom menu via the Rust backend. This will allow us to add a custom menu item to our app menu with a specified id.

为了实现这一点,我们需要通过 Rust 后端实现一个自定义菜单。这将允许我们在应用菜单中添加一个带有指定 id 的自定义菜单项。

Once added, we can listen for menu click events on the backend and emit a window event to the frontend.

添加完成后,我们可以在后端监听菜单点击事件,并通过 emit 向前端发送窗口事件。

On the frontend, we can listen for this custom event and trigger the desired action which, in my case, will be navigating to the /settings page.

在前端,我们可以监听这个自定义事件,并触发所需的操作,在我的例子中,就是导航到 /settings 页面。

Here’s what the code looks like:

代码如下:

In your main.rs file, we will create a menu with various submenus as required (e.g. File, Edit, Help etc). From what I understand, menus can be created either globally or per window. I currently only have a single window in my app, so I opted for a global menu.

在你的 main.rs 文件中,我们将创建一个包含各种所需子菜单的菜单(例如 File、Edit、Help 等)。据我了解,菜单可以全局创建,也可以按窗口创建。我目前的应用只有一个窗口,因此我选择了全局菜单。

I added my custom Settings... menu item to the App submenu, which is the submenu that appears when you click on the app name in the top menu bar on macOS.

我将自定义的 Settings... 菜单项添加到了 App 子菜单中,这个子菜单在 macOS 上点击顶部菜单栏中的应用名称时出现。

Once we have created the menu, we can use app.on_menu_event() to listen for the menu item click event on the backend and emit a browser window event to our frontend as follows:

创建菜单后,我们可以使用 app.on_menu_event() 在后端监听菜单项点击事件,并通过 emit 向我们的前端发送浏览器窗口事件,如下所示:

use tauri::{ menu::{AboutMetadata, MenuBuilder, MenuItemBuilder, SubmenuBuilder}, Manager,
}; fn main() { tauri:...
开通本站会员,查看完整译文。

ホーム - Wiki
Copyright © 2011-2025 iteam. Current version is 2.145.0. UTC+08:00, 2025-08-24 06:38
浙ICP备14020137号-1 $お客様$