欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 美食 > 【Tauri2】015——前端的事件、方法和invoke函数

【Tauri2】015——前端的事件、方法和invoke函数

2025/5/7 3:58:14 来源:https://blog.csdn.net/qq_63401240/article/details/147003241  浏览:    关键词:【Tauri2】015——前端的事件、方法和invoke函数

目录

前言

正文

准备

关键url

获取所有命令

切换主题set_theme

设置大小

获得版本version

名字name

监听窗口移动


前言

【Tauri2】005——tauri::command属性与invoke函数-CSDN博客https://blog.csdn.net/qq_63401240/article/details/146581991?spm=1001.2014.3001.5502

【Tauri2】013——前端Window Event与创建Window-CSDN博客https://blog.csdn.net/qq_63401240/article/details/146981362?spm=1001.2014.3001.5502

笔者在013这篇文章中,发现window中事件,本质是在发送一个请求,还是post。笔者想尝试能否自己发送一个请求。

正文

准备

首先,笔者以window.hide()作为研究对象。需要隐藏的权限

主要代码

import {getCurrentWindow} from "@tauri-apps/api/window";export default function useWindowEvent() {let window = getCurrentWindow();window.onMoved((event) => {window.hide()})
}
  "permissions": [..."core:window:allow-hide"]

上面代码的意思是,移动事件中,触发隐藏窗口。

关键url

首先,可以在开发者工具发现这样的url

http://ipc.localhost/plugin%3Awindow%7Chide

设置断点

断的位置如下

首先,这个断下的文件的名字,笔者叫vm45,

vm是Virtual Machine的缩写,表示这段代码是在浏览器的虚拟机环境中运行的,这就很麻烦了

 可以发现Tauri-CallbackTauri-Error,Tauri-Invoke-Key

这三个参数是非常关键的

笔者发现Tauri-CallbackTauri-Error,都是数字,后面再说

Tauri-Invoke-Key的定义如下

const __TAURI_INVOKE_KEY__ = JSON.parse('"Oeln}Dgql8BzP843PEb!"')

但是每次运行,都不一样。笔者也不知道如何生成的。

不改变,继续使用,会报错,比如

__TAURI_INVOKE_KEY__ expected jW%TgoDn{gagRJ==SGXq but received !sN1d=nrX)Eqc&J(GS*f

 __TAURI_INVOKE_KEY__ 不对

但是,笔者在控制台报了这个错,然后再修改了__TAURI_INVOKE_KEY__ ,窗口就消失了,就成功了。哈哈哈哈

笔者在测试中发现了这个,没有用

INVOKE_KEY in tauri::test - RustThe invoke key used for tests.https://docs.rs/tauri/latest/tauri/test/constant.INVOKE_KEY.html

上面还有一段注释

  /**
   * A runtime generated key to ensure an IPC call comes from an initialized frame.
   *
   * This is declared outside the `window.__TAURI_INVOKE__` definition to prevent
   * the key from being leaked by `window.__TAURI_INVOKE__.toString()`.
   */

居然是运行时生成的。还防止泄露,可以

看来想自己发送请求,自己创造这个__TAURI_INVOKE_KEY__ ,不可行,反正笔者没有成功。

后面来实现这段代码。

看看messsage

{"cmd": "plugin:window|hide","callback": 1804441640,"error": 3457847102,"payload": {"label": "main"}
}

看到cmd,发现可以传递给invoke,因此,如下代码也可以实现隐藏

import {getCurrentWindow} from "@tauri-apps/api/window";
import {invoke} from "@tauri-apps/api/core";export default function useWindowEvent() {let window = getCurrentWindow();window.onMoved((event) => {invoke("plugin:window|hide", {"label": "main"})})
}

需要设置权限。

运行成功。哈哈哈哈

如果笔者把plugin:window|hide改成hide,url变成了

http://ipc.localhost/hide

 当然,结果报错。

看来url就是http://ipc.localhost/+cmd,原来如此。

而且观察cmd的格式plugin:window|hide

应该是  plugin:<plugin_name>|<plugin_function>

获取所有的cmd

笔者在tauri::command这个属性中,其中的wrapper中,进行了打印,如下。

  println!("函数名: {}", function.sig.ident);

打印结果如下,笔者把它全部输出了

函数名: version                                                                                                                                                                    
函数名: name
函数名: tauri_version
函数名: identifier
函数名: app_show
函数名: app_hide
函数名: fetch_data_store_identifiers
函数名: remove_data_store
函数名: default_window_icon
函数名: set_app_theme
函数名: listen                                                                                                                                                                     
函数名: unlisten
函数名: emit
函数名: emit_to
函数名: fetch
函数名: close                                                                                                                                                                      
函数名: get_all_webviews
函数名: create_webview_window
函数名: create_webview
函数名: webview_position
函数名: webview_size
函数名: print
函数名: webview_close
函数名: set_webview_size
函数名: set_webview_position                                                                                                                                                       
函数名: set_webview_focus
函数名: webview_hide
函数名: webview_show
函数名: set_webview_zoom
函数名: set_webview_background_color
函数名: clear_all_browsing_data
函数名: reparent
函数名: internal_toggle_devtools
函数名: get_all_windows
函数名: create
函数名: scale_factor
函数名: inner_position
函数名: outer_position
函数名: inner_size
函数名: outer_size
函数名: is_fullscreen
函数名: is_minimized
函数名: is_maximized
函数名: is_focused
函数名: is_decorated                                                                                                                                                               
函数名: is_resizable
函数名: is_maximizable
函数名: is_minimizable
函数名: is_closable
函数名: is_visible
函数名: is_enabled
函数名: title
函数名: current_monitor
函数名: primary_monitor
函数名: available_monitors
函数名: cursor_position
函数名: theme
函数名: is_always_on_top
函数名: center
函数名: request_user_attention
函数名: set_resizable
函数名: set_maximizable
函数名: set_minimizable
函数名: set_closable
函数名: set_title
函数名: maximize
函数名: unmaximize
函数名: minimize
函数名: unminimize
函数名: show
函数名: hide
函数名: close
函数名: destroy
函数名: set_decorations                                                                                                                                                            
函数名: set_shadow
函数名: set_effects
函数名: set_always_on_top
函数名: set_always_on_bottom
函数名: set_content_protected
函数名: set_size
函数名: set_min_size
函数名: set_max_size
函数名: set_position
函数名: set_fullscreen
函数名: set_focus
函数名: set_skip_taskbar
函数名: set_cursor_grab
函数名: set_cursor_visible
函数名: set_background_color
函数名: set_cursor_icon
函数名: set_cursor_position
函数名: set_ignore_cursor_events
函数名: start_dragging
函数名: start_resize_dragging
函数名: set_progress_bar
函数名: set_badge_count
函数名: set_visible_on_all_workspaces
函数名: set_title_bar_style
函数名: set_size_constraints
函数名: set_theme
函数名: set_enabled
函数名: set_overlay_icon
函数名: set_icon
函数名: toggle_maximize
函数名: internal_toggle_maximize
函数名: monitor_from_point
函数名: new                                                                                                                                                                        
函数名: from_bytes
函数名: from_path
函数名: rgba
函数名: size
函数名: new                                                                                                                                                                        
函数名: append
函数名: prepend
函数名: insert
函数名: remove
函数名: remove_at
函数名: items
函数名: get
函数名: popup
函数名: create_default
函数名: set_as_app_menu                                                                                                                                                            
函数名: set_as_window_menu
函数名: text
函数名: set_text
函数名: is_enabled
函数名: set_enabled
函数名: set_accelerator
函数名: set_as_windows_menu_for_nsapp
函数名: set_as_help_menu_for_nsapp
函数名: is_checked
函数名: set_checked
函数名: set_icon
函数名: resolve_directory                                                                                                                                                          
函数名: resolve
函数名: normalize
函数名: join
函数名: dirname
函数名: extname
函数名: basename
函数名: is_absolute

这些都是方法,笔者不敢确定是否都可以用

笔者尝试了一些方法

切换主题set_theme

需要权限  ——"core:window:allow-set-theme"

import './App.css'
import {getCurrentWindow} from "@tauri-apps/api/window";function App() {let window = getCurrentWindow();async function handleClick() {let get_theme = await window.theme();if(get_theme === "dark") {await window.setTheme("light");}else {await window.setTheme("dark");}}return (<><header><h1>My Tauri App</h1></header><main><div style={{ display: 'flex', gap: '10px' }}><button onClick={handleClick}>点击</button></div></main></>);
}export default App;

第二个url及负载

http://ipc.localhost/plugin%3Awindow%7Ctheme

label: "main"

第三个url及负载

http://ipc.localhost/plugin%3Awindow%7Cset_theme

label: "main"

value: "light"

 根据上面的信息,使用invoke实现的代码如下

    async function handleClick() {let get_theme = await invoke('plugin:window|theme',{'label':'main'});console.log(get_theme);if(get_theme === "dark") {await invoke('plugin:window|set_theme',{'label':'main','value':'light'});}else {await invoke('plugin:window|set_theme',{'label':'main','value':'dark'});}}

结果是成功的,哈哈哈哈哈哈

当然,感觉没什么用,相对来说,搞麻烦了。

但是,想不到这个invoke函数居然是这么关键,居然可以这样操作。

设置大小

再来试试,

权限core:window:allow-set-size

    async function handleClick() {let get_size=await window.innerSize();console.log(get_size);window.setSize(new PhysicalSize(1000, 500));}

观察请求

http://ipc.localhost/plugin%3Awindow%7Cinner_size

{label: "main"}

http://ipc.localhost/plugin%3Awindow%7Cset_size

{
  "label": "main",
  "value": {
    "Physical": {
      "width": 1000,
      "height": 500
    }
  }

因此,代码如下

    async function handleClick() {await invoke("plugin:window|set_size", {"label": "main","value": {"Physical": {"width": 1000,"height": 500}}});}

结果是可以的。哈哈哈哈

获得版本version

直接给出代码

    async function handleClick() {let version=await invoke("plugin:app|version")console.log("版本:",version)}

名字name

    async function handleClick() {let name=await invoke("plugin:app|name")console.log("名字:",name)}

 

监听窗口移动

简单地代码如下

import { getCurrentWindow } from "@tauri-apps/api/window";export async function useWindowEvent() {const window = getCurrentWindow();window.onMoved(()=>{console.log("窗口移动了");})}
onMoved(handler: EventCallback<PhysicalPosition>): Promise<UnlistenFn>;

 或者用listen,差不多。

使用invoke,应该怎么办?

先看看请求

http://ipc.localhost/plugin%3Aevent%7Clisten

{
  "event": "tauri://move",
  "target": {
    "kind": "Window",
    "label": "main"
  },
  "handler": 3468365674
}

这里面有个handler,很明显,是用来处理移动后的事件

如何自定义handler?

这就需要一个函数了——transformcallback

core | Taurihttps://v2.tauri.app/reference/javascript/api/namespacecore/#transformcallback

declare function transformCallback<T = unknown>(callback?: (response: T)=> void, once?: boolean): number;

第一个参数callback 是一个函数

第二个可选参数once 是boolean,判断是否使用一次。

返回一个数字

在前面,笔者提到,“Tauri-CallbackTauri-Error,都是数字”,很有可能就是这个函数的返回值。

综合上面的信息

最后,代码如下

import {transformCallback,invoke} from "@tauri-apps/api/core";
import {Event} from '@tauri-apps/api/event'export async function useWindowEvent() {const handlerId = transformCallback((event:Event<unknown>) => {console.log("窗口移动事件通过invoke实现:", event.payload);});await invoke("plugin:event|listen", {event: "tauri://move",target: { kind: "Window", label: "main" },handler: handlerId});
}

窗口隐藏

前面说了这么多,都是使用invoke,最后使用一下fetch

直接给出代码

import {transformCallback} from "@tauri-apps/api/core";
import {Event} from "@tauri-apps/api/event";export async function useWindowEvent() {const error=transformCallback((event:Event) => {console.log("失败")})const success=transformCallback((event:Event) => {console.log("成功")})const __TAURI_INVOKE_KEY__ = JSON.parse('"lZzIiQJ%t9b@}Q&aef^A"')fetch("http://ipc.localhost/plugin%3Awindow%7Chide", {method: 'POST',body: JSON.stringify({'label': 'main',}),headers: {'Content-Type': "application/json",'Tauri-Callback': success,'Tauri-Error': error,'Tauri-Invoke-Key': __TAURI_INVOKE_KEY__,}})}

笔者在代码中替换了,最后,成功了

怎么处理回调函数,笔者也不知道。

笔者还发现,只要不关闭程序,这个__TAURI_INVOKE_KEY__就可以使用

最后,虽然没有什么用。

哈哈哈哈

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词