Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Illegal Invocation" error on simple script

Tags:

javascript

I want to mess around with Speech Recognition API, so I started with the simple page which starts recognition on click on body element. My scripts.js file is:

var recognition = new window.webkitSpeechRecognition();
document.body.addEventListener("click", recognition.start, false);

Now when I click anywhere on body element I have the strange error in Chrome console:

Uncaught TypeError: Illegal invocation

It refers to first line of my HTML code. My HTML file is:

<!DOCTYPE html>
<html lang="en">
<head>
    <title></title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <script src="scripts.js"></script>
</body>
</html>

How do I fix this weird error?

like image 622
1valdis Avatar asked Apr 24 '26 02:04

1valdis


1 Answers

Youre loosing context:

document.body.addEventListener("click", recognition.start, false);

Is equal to:

var start = recognition.start;
document.body.addEventListener("click", start, false);

So inside of start, this will refer to window, and windows cannot speak. To resolve it, bind:

document.body.addEventListener("click", recognition.start.bind(recognition), false);

or use a function inbetween:

document.body.addEventListener("click", _=>recognition.start(), false);
like image 172
Jonas Wilms Avatar answered Apr 25 '26 14:04

Jonas Wilms



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!