The examples below show few ways to handle permissions using Speech API.
<!-- Anywhere in the page -->
<script>
/** When the document has been loaded, iterate through all the
* reco elements and remove the ones which have request.authorizationState
* SPEECH_AUTHORIZATION_NOT_AUTHORIZED. For the rest of the reco elements
* add authorizationchange event listener, which will remove the target of
* the event from DOM if its request.authorizationState changes to
*/ SPEECH_AUTHORIZATION_NOT_AUTHORIZED.
window.addEventListener("load",
function() {
var recos = document.getElementsByTagName("reco");
for (var i = recos.length - 1; i >= 0; --i) {
if (!removeNotAuthorizedReco(recos[i])) {
recos[i].addEventListener("authorizationchange",
function(evt) { removeNotAuthorizedReco(evt.target); });
}
}
});
function removeNotAuthorizedReco(reco) {
if (reco.request.authorizationState ==
SpeechInputRequest.SPEECH_AUTHORIZATION_NOT_AUTHORIZED) {
reco.parentNode.removeChild(reco);
return true;
}
return false;
}
</script>
<!-- Anywhere in the page -->
<script>
var request; // Make sure the request object is kept alive.
window.addEventListener("load",
function () {
request = new SpeechRequest();
request.onresult =
function(evt) {
// Do something with the speech recognition result.
}
request.open(); // Trigger permission handling UI in the user agent.
document.addEventListener("click",
function() {
if (request.authorizationState ==
SpeechInputRequest.SPEECH_AUTHORIZATION_AUTHORIZED) {
request.start();
}
});
});
</script>