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...
菜单项。当点击这个菜单项时,我希望前端网页视图导航到 /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
文件中,我们将创建一个包含各种子菜单的菜单(例如:文件、编辑、帮助等)。根据我的理解,菜单可以全局创建或每个窗口创建。我目前在我的应用中只有一个窗口,所以我选择了全局菜单。
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::Buil...