How to fix an issue when window in undefined in tauri?
Asked Answered
E

3

6

I am new at tauri and I have faced the issue with getting data from @tauri-apps/api.

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

This is my React code below:

/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

{
   "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)
Elkeelkhound answered 22/9, 2022 at 15:26 Comment(0)
H
7

The typical 2 sources for this kind of error are:

  1. you're in a SSR environment - This could be a problem with next.js for example, but not with plain React.
  2. you're viewing the frontend in your browser - Tauri's APIs are only injected into actual Tauri windows.
Hinkel answered 22/9, 2022 at 17:46 Comment(2)
I guess the solution is just not to use Next.JS for Tauri? I'll try using ViteJS instead.Antoninaantonino
@Antoninaantonino That would probably be the easiest solution, but it's not necessary per se. You just need to be careful because some nextjs features don't work when you use next export and you need to use dynamic imports for the window and path modules to make sure they are only imported on the client-side, etc.Hinkel
D
2

Seems like if you import anything from the root package of @tauri-apps/api, it seems like it tries to access the global window instance before the window initializes (?), which is undefined.

My problem was to use invoke to request some data from Rust side. FabianLars's answer on Github helped me. Basically, whenever you want to import something from @tauri-apps/api, just import it from a submodule.

// instead of this
import { invoke } from "@tauri-apps/api";

// do this
import { invoke } from "@tauri-apps/api/tauri";
Ddt answered 10/10, 2023 at 9:33 Comment(1)
Seems like they removed the export from @tauri-apps/api, so you can only import invoke from the submodule. Thus, the problem seems to be resolved.Ddt
C
0

You can write a function to judge

const handleIsTauri = () => {
    return Boolean(
  typeof window !== 'undefined' &&
  window !== undefined &&
  window.__TAURI_IPC__ !== undefined
)};
Coze answered 30/11, 2022 at 10:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.