tauri开发中在initialization_script自定义的js脚本中调用tauri事件api

297 阅读1分钟

官方文档:v1.tauri.app/v1/api/conf…

一定要把withGlobalTauri这个设置为true,才可以在全局使用tauri的api,而且还要配置

dangerousRemoteDomainIpcAccess,在里面添加要通讯的窗口的label和域名,也要开启
enableTauriAPI为true。

在以上两个地方都配置了true之后,就可以在js中使用了:

window.addEventListener('DOMContentLoaded', () => {
    if (window.__TAURI__) {
        console.log('Tauri API loaded:', window.__TAURI__.event)
        window.__TAURI__.event.listen('handlepay', (data) => {
            console.log('Received example-event:', data)
        })
    } else {
        console.error('Tauri API not available!')
    }
})

注意要在页面加载完之后,再使用,不然不一定给window对象绑定了__TAURI__属性,所以要等DOMContentLoaded,然后就可以了。