Search code examples
sveltevitewebspeech-api

How to use the WebSpeech API in svelte


I am working on a frontend project which involves the use of the google WebSpeech API. When I try to declare the speech recognition, I get errors saying speech recognition is not defined or window is not defined. The project fails to compile. How do I fix this?

The code inside my tag is below;

const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
const recognition = new SpeechRecognition();

This is the error

window is not defined ReferenceError: window is not defined

I am using vite-plugin-svelte for compiling & Chrome browser for testing.


Solution

  • The window object doesn't exist on the server, so you need to make sure it is only used in the browser.

    You could e.g. initialize recognition in the browser only with onMount.

    Example

    <script>
      import { onMount } from 'svelte';
    
      let recognition;
    
      onMount(() => {
        const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
        recognition = new SpeechRecognition();
      });
    </script>