简体   繁体   English

如何解决 window 在 tauri 中未定义的问题?

[英]How to fix an issue when window in undefined in tauri?

I am new at tauri and I have faced the issue with getting data from @tauri-apps/api.我是 tauri 的新人,我遇到了从@tauri-apps/api 获取数据的问题。

"@tauri-apps/api": "^1.1.0",
"@tauri-apps/cli": "^1.1.1"

This is my React code below:下面是我的 React 代码:

/index.jsx

import {getTauriVersion} from "@tauri-apps/api/app"
function App() {
   const func = async () => {
       const res = await getTauriVersion()
       return res    
   }
   return (<></>)
}

This is my tauri.conf.json这是我的 tauri.conf.json

{
   "build": {
    "beforeDevCommand": "npm run dev",
    "beforeBuildCommand": "npm run build",
    "devPath": "http://localhost:1420",
    "distDir": "../dist",
    "withGlobalTauri": true
  },
  ...
  "tauri": {
     "allowList": {"all": true}
  }
}

And the error is:错误是:

Uncaught (in promise) TypeError: window.__TAURI_IPC__ is not a function
unhandledRejection: ReferenceError: window is not defined
at o (file:///C:/test/test/node_modules/@tauri-apps/api/tauri- 
a4b3335a.js:1:100)

The typical 2 sources for this kind of error are:此类错误的典型 2 个来源是:

  1. you're in a SSR environment - This could be a problem with next.js for example, but not with plain React.您在 SSR 环境中 - 例如,这可能是 next.js 的问题,但不是普通的 React。
  2. you're viewing the frontend in your browser - Tauri's APIs are only injected into actual Tauri windows.您正在浏览器中查看前端 - Tauri 的 API 仅注入实际的 Tauri windows。

You can write a function to judge可以写个function来判断

const handleIsTauri = () => {
    return Boolean(
  typeof window !== 'undefined' &&
  window !== undefined &&
  window.__TAURI_IPC__ !== undefined
)};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM