From 738e23da41cde281387b360ee084dfa3c16ddd1b Mon Sep 17 00:00:00 2001 From: Kenneth Kufluk Date: Thu, 27 Jan 2022 15:30:36 -0800 Subject: [PATCH] Update speech-color-changer to be compatible with Safari Safari does not currently implement webkitSpeechGrammarList and throws an error at line 2. I have guarded against this, so the script now works in Safari on desktop and iPhone. I've also added a comment around the grammar code because no browser currently supports them, as noted in this WICG discussion: https://github.com/WICG/speech-api/issues/57 Since we'll check usage stats to determine if grammars should be removed from the spec, and this script encourages grammar usage (I imagine this code will be copy/pasted assuming they have an effect), I added a comment to discourage their use. I didn't want to remove grammars completely, as this script is used as a demonstration of the spec on MDN. --- speech-color-changer/script.js | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/speech-color-changer/script.js b/speech-color-changer/script.js index 54ffc2a..cbd0d5a 100644 --- a/speech-color-changer/script.js +++ b/speech-color-changer/script.js @@ -1,14 +1,18 @@ var SpeechRecognition = SpeechRecognition || webkitSpeechRecognition -var SpeechGrammarList = SpeechGrammarList || webkitSpeechGrammarList +var SpeechGrammarList = SpeechGrammarList || window.webkitSpeechGrammarList var SpeechRecognitionEvent = SpeechRecognitionEvent || webkitSpeechRecognitionEvent var colors = [ 'aqua' , 'azure' , 'beige', 'bisque', 'black', 'blue', 'brown', 'chocolate', 'coral', 'crimson', 'cyan', 'fuchsia', 'ghostwhite', 'gold', 'goldenrod', 'gray', 'green', 'indigo', 'ivory', 'khaki', 'lavender', 'lime', 'linen', 'magenta', 'maroon', 'moccasin', 'navy', 'olive', 'orange', 'orchid', 'peru', 'pink', 'plum', 'purple', 'red', 'salmon', 'sienna', 'silver', 'snow', 'tan', 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'white', 'yellow']; -var grammar = '#JSGF V1.0; grammar colors; public = ' + colors.join(' | ') + ' ;' var recognition = new SpeechRecognition(); -var speechRecognitionList = new SpeechGrammarList(); -speechRecognitionList.addFromString(grammar, 1); -recognition.grammars = speechRecognitionList; +if (SpeechGrammarList) { + // SpeechGrammarList is not currently available in Safari, and does not have any effect in any other browser. + // This code is provided as a demonstration of possible capability. You may choose not to use it. + var speechRecognitionList = new SpeechGrammarList(); + var grammar = '#JSGF V1.0; grammar colors; public = ' + colors.join(' | ') + ' ;' + speechRecognitionList.addFromString(grammar, 1); + recognition.grammars = speechRecognitionList; +} recognition.continuous = false; recognition.lang = 'en-US'; recognition.interimResults = false;