Reputation: 1104
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?
Upvotes: 3
Views: 864
Reputation: 138257
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);
Upvotes: 3