tauri-apps / tauri

Build smaller, faster, and more secure desktop applications with a web frontend.
https://tauri.app
Apache License 2.0
81.22k stars 2.43k forks source link

[bug] window.__TAURI_IPC__ is not a function #3434

Closed davidhaley closed 2 years ago

davidhaley commented 2 years ago

Describe the bug

I followed the documentation to create my first app using: yarn create tauri-app

I receive an error when trying to run a basic echo command.

Thank you.

Reproduction

  1. yarn create tauri-app
  2. Choose Svelte w/ Typescript
  3. cd <app_name>
  4. yarn install
  5. yarn tauri dev
  6. Add the following as code inside the script/main tags:
<script lang="ts">
    import { Command } from '@tauri-apps/api/shell';
    export let name: string;

    const command = new Command('echo', 'message').execute();
</script>

<main>
    <h1>Hello {name}!</h1>
    {#await command}
        <p>waiting...</p>
    {:then output}
        <p>output: {output}</p>
    {:catch error}
        <p style="color: red">{error.message}</p>
    {/await}
</main>
  1. Notice the error printed to the page: window.__TAURI_IPC__ is not a function
  2. Check the window in the console (it doesn't exist)

Expected behavior

'message' is returned

Platform and versions

> monocole@1.0.0 tauri
> tauri "info"

Operating System - EndeavourOS, version Rolling Release X64

Node.js environment
  Node.js - 17.5.0
  @tauri-apps/cli - 1.0.0-rc.2
  @tauri-apps/api - 1.0.0-rc.0

Global packages
  npm - 8.4.1
  pnpm - Not installed
  yarn - 1.22.17

Rust environment
  rustc - 1.58.1
  cargo - 1.58.0

Rust environment
  rustup - 1.24.3
  rustc - 1.58.1
  cargo - 1.58.0
  toolchain - stable-x86_64-unknown-linux-gnu 

App directory structure
/public
/src
/.vscode
/node_modules
/src-tauri

App
  tauri.rs - 1.0.0-rc.1
  build-type - bundle
  CSP - default-src 'self'
  distDir - ../public
  devPath - http://localhost:8080/
  framework - Svelte
  bundler - Rollup

Stack trace

None

Additional context

Firefox 97.0 (64-bit)

Kernel: uname -r > 5.15.21-hardened1-1-hardened

amrbashir commented 2 years ago

tauri apis needs the window object and thus should be called when the component is mounted. try using svelte onMounted and call the command there

amrbashir commented 2 years ago

Please reopen if the issue persists with onMounted

davidhaley commented 2 years ago

Hello @amrbashir,

I'm not sure how to re-open the issue; however, the error still occurs even when placed inside onMount().

<script lang="ts">
    import { Command } from '@tauri-apps/api/shell';
    import { onMount } from 'svelte';

    export let name: string;

    let command;
    onMount(() => {
        command = new Command('echo', 'message').execute();
    })
</script>

<main>
    <h1>Hello {name}!</h1>
    {#await command}
        <p>waiting...</p>
    {:then output}
        <p>output: {output}</p>
    {:catch error}
        <p style="color: red">{error.message}</p>
    {/await}
</main>

Alternative attempt results in the same issue:

<script lang="ts">
    import { Command } from '@tauri-apps/api/shell';
    import { onMount } from 'svelte';

    export let name: string;

    let output;
    onMount(async () => {
        try {
            output = await new Command('echo', 'message').execute();
        } catch(e) {
            console.error(e)
        }
    })
</script>

<main>
    {output}
</main>
davidhaley commented 2 years ago

Wait a second, I think this is a misunderstanding on my part.

After creating the project and following the instructions to run it, I ran into the error.

The issue is that I was starting the project with yarn run dev. I checked package.json and saw there is a tauri script, and when run, it outputs there is a dev sub-command. Running npm run tauri dev builds and runs the app in a window (rather than the browser), and TAURI exists on the window now.

I see a new error: program not allowed on the configured shell scope: echo; however, I suspect that is corrected in the tauri.conf.json, so I'll follow the docs from here.

Thank you for your time!

FabianLars commented 2 years ago

Yeah, the tauri scripts are only injected into tauri windows :)

Zenahr commented 1 year ago

This bug still happens with a fresh Tauri installation. (Windows 10, React javascript boilerplate chosen)

abulka commented 1 year ago

Me too. I followed a fresh Tauri installation on my Mac, specifying Vue and Typescript frontend npm create tauri-app@latest, installed the npm packages, then ran npm run tauri dev and got the web page appearing ok.

But clicking Greet gives me the same error.

[Vue warn]: Unhandled error during execution of native event handler 
  at <Greet> 
  at <App>
warn2 @ runtime-core.esm-bundler.js:40
chunk-RCPA6UVN.js:1 Uncaught (in promise) TypeError: window.__TAURI_IPC__ is not a function
    at chunk-RCPA6UVN.js:1:542
    at new Promise (<anonymous>)
    at c (chunk-RCPA6UVN.js:1:397)
    at Proxy.greet (Greet.vue:10:26)
    at _createElementVNode.onClick._cache.<computed>._cache.<computed> (Greet.vue:17:35)
    at callWithErrorHandling (runtime-core.esm-bundler.js:173:22)
    at callWithAsyncErrorHandling (runtime-core.esm-bundler.js:182:21)
    at HTMLButtonElement.invoker (runtime-dom.esm-bundler.js:345:9)

Why would the recommended default app be broken - for over a year now? Am I missing something?

P.S. Then building the app with the recommended npm run tauri build gives me

   Compiling embed_plist v1.2.2
    Finished release [optimized] target(s) in 12m 02s
    Bundling tauri-app-andy.app (/Users/andy/Devel/tauri-electron-alternative/tauri-app/src-tauri/target/release/bundle/macos/tauri-app-andy.app)
    Bundling tauri-app-andy_0.0.0_x64.dmg (/Users/andy/Devel/tauri-electron-alternative/tauri-app/src-tauri/target/release/bundle/dmg/tauri-app-andy_0.0.0_x64.dmg)
     Running bundle_dmg.sh
       Error failed to bundle project: error running bundle_dmg.sh: error running bundle_dmg.sh: `failed to run /Users/andy/Devel/tauri-electron-alternative/tauri-app/src-tauri/target/release/bundle/dmg/bundle_dmg.sh`

Not a good introductory experience. I must have missed something in the installation? I installed cargo and ran all the npm commands and created the default project.

dwhyte19 commented 1 year ago

This is not a good look for Tauri, since it's literally supposed to be install, run and play.

FabianLars commented 1 year ago

We're not aware of any issues with the templates as long as you use the tauri window. Again, opening the frontend in your default browser is not supported.

If you encounter any issues, please post the following things: 1) The reproduction steps 2) The problematic code, at least if it's not from the starter template - preferably the whole git project 3) The output of npm run tauri info (swap npm with the package manager you're using) 4) A screenshot of the error showing that it's from inside a tauri window - apologies for requiring this but this is a really common mistake

dwhyte19 commented 1 year ago

That makes sense. I think it would be great to really clarify this in the documentation/readme, since it's a common mistake.

ivanglushko commented 1 year ago

I've fallen into it as well. As i run yarn dev which starts vite in web browser. I've used yarn create tauri-app.

Zenahr commented 1 year ago

for me the error was solved by installing Rust. Although I read through the docs, I thought that I won't be needing that. Perhaps making it even more clear (e.g., with a red callout) that you need Rust set up on your machine first would make less people face this issue.

Another improvement could be to catch this specific error and add an additional note to the error message asking if you've installed Rust correctly on your machine.

ethan-sargent commented 1 year ago

@FabianLars To reproduce:

cargo install create-tauri-app
cargo create-tauri-app
✔ Project name · tauri-test
✔ Choose which language to use for your frontend · TypeScript / JavaScript - (pnpm, yarn, npm)
✔ Choose your package manager · yarn
✔ Choose your UI template · Vanilla
✔ Choose your UI flavor · TypeScript

cd tauri-test
yarn
yarn dev

Note that I ran yarn dev, not yarn tauri dev. This will launch the app in a browser window, causing the issue above.

Expected outcome: The "dev" script in the package json should not launch a browser window given this is explicitly not supported.

FabianLars commented 1 year ago

Hmm, it never opened the default browser for me so i wasn't aware that it does that. If you add open: false, to the server config in vite.config.js|ts does it stop doing that then? (If so, we'll add that to the templates). Thank you.

amrbashir commented 1 year ago

Note that I ran yarn dev, not yarn tauri dev.

This is the issue, you should not run yarn dev, always run yarn tauri dev as the post-template instructions says.

FabianLars commented 1 year ago

While that is true, yarn tauri dev will invoke yarn dev, so if the latter opens up a browser automatically then yarn tauri dev should too in this context.

amrbashir commented 1 year ago

All don't open the browser by default, and I just tested Vanilla -> Typescript and it didn't open the browser.

ethan-sargent commented 1 year ago

@amrbashir @FabianLars, even if it may not open automatically in browser - the tauri app naturally doesn’t pop up when running yarn dev because it hasn’t been invoked. The next step for anyone who has used vite outside of Tauri is to click on the link to view the app. This is poor UX, since yarn dev is the standard command to run the local development version of an app for the rest of the ecosystem.

I believe the yarn dev command should be properly starting the tauri app, or the yarn dev script should be renamed/removed from the package json file if it’s only for internal use by Tauri.

amrbashir commented 1 year ago

The yarn dev script is kept there for two reasons:

  1. Because tauri cli will run it before starting the tauri app in development, so you get HMR and such
  2. To allow development of the web app independently, because you may need to have a webapp and a native app using the same codebase

When you create a tauri app using create-tauri-app tool it will give you instructions to:

cd tauri-app
yarn
yarn tauri dev

now my question is, did you not notice the instructions? should we make the instructions more colorful or maybe bolder?

ethan-sargent commented 1 year ago

@amrbashir I'm confused about this given your previous response:

you should not run yarn dev, always run yarn tauri dev

If yarn dev has a legitimate use case, then maybe it would be helpful for the project template to be set up so that it demonstrates when/how you would want to use this? Something like "hello from the front end/from WASM" instead of "hello from Rust".

I noticed the instructions, but given I've used yarn before I did assume incorrectly that I would follow the same process to start the dev server instance as I would elsewhere. Maybe the instructions could be more clear, or maybe we could print something before we start vite so that it's clear that it's running the front-end only and rust FFI will not work?

It might be more powerful/ergonomic to have some fallback for tauri IPC failing in a web app context, so that we don't need to have multiple code paths in client side code to choose a path based on web app usage vs tauri app usage. This would be well out of scope for this issue though.

amrbashir commented 1 year ago

If yarn dev has a legitimate use case, then maybe it would be helpful for the project template to be set up so that it demonstrates when/how you would want to use this? Something like "hello from the front end/from WASM" instead of "hello from Rust".

I am just saying it is an option to have web/tauri-app project from single codebase but the template is tailored towards tauri (with the possiblity for future hybrid project). In addition to that, we still need yarn dev to exist so yarn tauri dev could run it before opening the tauri app.

Maybe the instructions could be more clear, We would love some feedback on how we should make it more clear.

or maybe we could print something before we start vite so that it's clear that it's running the front-end only and rust FFI will not work?

It does, the CLI prints

Running beforeDevCommand ('yarn dev')

It might be more powerful/ergonomic to have some fallback for tauri IPC failing in a web app context, so that we don't need to have multiple code paths in client side code to choose a path based on web app usage vs tauri app usage. This would be well out of scope for this issue though.

What kind of a fallback do you have in mind? because tauri IPC can't work in a browser at all, it has to be a tauri window.

I think we could maybe try to detect that tauri APIs are loaded on a browser and maybe console.err that tauri APIs doesn't work in a normal browser and you may have missed a tauri specific guard or just used the wrong npm script.

JameelKhan9 commented 11 months ago

Just stumbled across this while using create tauri-app as I ran pnpm dev instead of pnpm tauri dev. I started to think the Greet functionality in the scaffolded app was broken.

I agree that a console error would be valuable, as this was the first place I looked to see what was happening.

I also think it is worth swapping pnpm dev to run tauri by default and change the vite web dev to pnpm vite dev as the fundamental purpose of this is to build a tauri app. I am seeing the same pattern with most of the tauri templates under awesome-tauri.

bennekrouf commented 6 months ago

Same issue while running : yarn && yarn tauri android init && yarn tauri android dev

$ tauri info

[✔] Environment

[-] Packages

[-] App

FabianLars commented 6 months ago

@bennekrouf Try updating your @tauri-apps/api package (in package.json) to 2.0.0-beta.0.

yerlibilgin commented 5 months ago

After updating to @tauri-apps/api@2.0.0-beta.3 the import fails: import {invoke} from '@tauri-apps/api'

I had to change it to: import {invoke} from "@tauri-apps/api/core"

then it worked.